Merge branch 'master' into feat/alerts-for-apps

This commit is contained in:
Christopher Gjelten authored and GitHub committed 2021-02-28 02:00:34 +01:00
commit 51f9b20857
79 files changed
+1716 -970

No files matched your search

+47 -57
View File
@@ -2,10 +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 { CallModal } from './modal/components/CallModal'; import { CallModal } from './os/call/components/CallModal';
import { HomeApp } from './apps/home/components/Home'; import { HomeApp } from './apps/home/components/Home';
import { ThemeProvider, Slide } from '@material-ui/core'; import { Slide } from '@material-ui/core';
import { useInitKeyboard } from './os/keyboard/hooks/useKeyboard'; import { useKeyboardService } from './os/keyboard/hooks/useKeyboardService';
import { NotificationBar } from './os/notifications/components/NotificationBar'; import { NotificationBar } from './os/notifications/components/NotificationBar';
import { Navigation } from './os/navigation-bar/components/Navigation'; import { Navigation } from './os/navigation-bar/components/Navigation';
import { useNuiService } from './os/nui-events/hooks/useNuiService'; import { useNuiService } from './os/nui-events/hooks/useNuiService';
@@ -21,33 +21,25 @@ import { useMessagesService } from './apps/messages/hooks/useMessageService';
import { useNotesService } from './apps/notes/hooks/useNotesService'; import { useNotesService } from './apps/notes/hooks/useNotesService';
import { usePhotoService } from './apps/camera/hooks/usePhotoService'; import { usePhotoService } from './apps/camera/hooks/usePhotoService';
import { useSettings } from './apps/settings/hooks/useSettings'; import { useSettings } from './apps/settings/hooks/useSettings';
import { useCallService } from './modal/hooks/useCallService'; import { useCallService } from './os/call/hooks/useCallService';
import { useModal } from './modal/hooks/useModal';
import { useDialService } from './apps/dialer/hooks/useDialService'; import { useDialService } from './apps/dialer/hooks/useDialService';
import InjectDebugData from './os/debug/InjectDebugData'; import InjectDebugData from './os/debug/InjectDebugData';
import { usePhoneVisibility } from './os/phone/hooks/usePhoneVisibility'; import { usePhoneVisibility } from './os/phone/hooks/usePhoneVisibility';
import { usePhoneTheme } from './os/phone/hooks/usePhoneTheme';
import { Snackbar } from './ui/components/Snackbar'; import { Snackbar } from './ui/components/Snackbar';
import { NotificationAlert } from './os/notifications/components/NotificationAlert';
import { useCallModal } from './os/call/hooks/useCallModal';
function Phone() { function Phone() {
const { modal } = useModal();
const { apps } = useApps(); const { apps } = useApps();
const [settings] = useSettings(); const [settings] = useSettings();
const {
bottom,
visibility,
uncollapseNotifications,
clickEventOverride,
} = usePhoneVisibility();
useNuiService(); useNuiService();
useKeyboardService();
usePhoneService(); usePhoneService();
useSimcardService(); useSimcardService();
useContactsService(); useContactsService();
useTwitterService(); useTwitterService();
useInitKeyboard();
useSelloutService(); useSelloutService();
useBankService(); useBankService();
useMessagesService(); useMessagesService();
@@ -56,58 +48,56 @@ function Phone() {
useCallService(); useCallService();
useDialService(); useDialService();
const currentTheme = usePhoneTheme(); const { modal: callModal } = useCallModal();
const { bottom, visibility } = usePhoneVisibility();
return ( return (
<ThemeProvider theme={currentTheme}> <Slide direction='up' in={visibility}>
<Slide direction='up' in={visibility} mountOnEnter unmountOnExit> <div className='PhoneWrapper'>
<div className='PhoneWrapper'> <div>
<div> <div
className='Phone'
style={{
transformOrigin: 'right bottom',
transform: `scale(${settings.zoom}`,
bottom,
}}
>
<div <div
onClick={clickEventOverride} className='PhoneFrame'
className='Phone'
style={{ style={{
transformOrigin: 'right bottom', backgroundImage: `url(./media/frames/${settings.frame})`,
transform: `scale(${settings.zoom}`, }}
bottom, />
<div
id='phone'
className='PhoneScreen'
style={{
backgroundImage: `url(./media/backgrounds/${settings.wallpaper})`,
}} }}
> >
<div <>
className='PhoneFrame' <NotificationBar />
style={{ <div className='PhoneAppContainer'>
backgroundImage: `url(./media/frames/${settings.frame})`, <>
}} <Route exact path='/' component={HomeApp} />
/> {callModal && (
<div <Route exact path='/call' component={CallModal} />
id='phone'
className='PhoneScreen'
style={{
backgroundImage: `url(./media/backgrounds/${settings.wallpaper})`,
}}
>
<>
<NotificationBar forceUncollapse={uncollapseNotifications} />
<div className='PhoneAppContainer'>
{modal ? (
<CallModal />
) : (
<>
<Route exact path='/' component={HomeApp} />
{apps.map((App) => (
<App.Route key={App.id} />
))}
</>
)} )}
<Snackbar /> {apps.map((App) => (
</div> <App.Route key={App.id} />
<Navigation /> ))}
</> </>
</div> <NotificationAlert />
<Snackbar />
</div>
<Navigation />
</>
</div> </div>
</div> </div>
</div> </div>
</Slide> </div>
</ThemeProvider> </Slide>
); );
} }
+21
View File
@@ -0,0 +1,21 @@
import React from 'react';
import { ThemeProvider } from '@material-ui/core';
import { BankNotification } from './apps/bank/components/notification/BankNotification';
import { NotificationsProvider } from './os/notifications/providers/NotificationsProvider';
import { usePhoneTheme } from './os/phone/hooks/usePhoneTheme';
import SnackbarProvider from './ui/providers/SnackbarProvider';
import Phone from './Phone';
export const PhoneContainer = () => {
const currentTheme = usePhoneTheme();
return (
<ThemeProvider theme={currentTheme}>
<NotificationsProvider>
<BankNotification />
<SnackbarProvider>
<Phone />
</SnackbarProvider>
</NotificationsProvider>
</ThemeProvider>
);
};
@@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { SvgIcon } from '@material-ui/core'; import { SvgIcon, SvgIconProps } from '@material-ui/core';
export const CalculatorIcon = ({ ...props }) => { export const CalculatorIcon = ({ ...props}: SvgIconProps) => {
return ( return (
<SvgIcon {...props}> <SvgIcon {...props}>
<svg <svg
@@ -16,7 +16,7 @@ InjectDebugData([
image: 'https://i.imgur.com/OO8wx6Z.jpg', image: 'https://i.imgur.com/OO8wx6Z.jpg',
}, },
{ {
id: 1, id: 2,
image: 'https://i.imgur.com/pqGBiST.jpg', image: 'https://i.imgur.com/pqGBiST.jpg',
}, },
], ],
@@ -27,12 +27,12 @@ export const GalleryModal = () => {
history.push(referal); history.push(referal);
}; };
const handleDeletePhoto = useCallback(() => { const handleDeletePhoto = () => {
Nui.send('photo:deletePhoto', { Nui.send('photo:deletePhoto', {
id: meta.id, image: meta.image,
}); });
history.push(referal); history.push(referal);
}, [history, meta.id, referal]); };
const handleSharePhoto = useCallback(() => { const handleSharePhoto = useCallback(() => {
setShareOpen(meta); setShareOpen(meta);
@@ -42,7 +42,11 @@ export const GalleryModal = () => {
return ( return (
<> <>
<ShareModal referal={referal} meta={shareOpen} onClose={() => setShareOpen(null)} /> <ShareModal
referal={referal}
meta={shareOpen}
onClose={() => setShareOpen(null)}
/>
<Paper className={classes.modal}> <Paper className={classes.modal}>
<div className={shareOpen ? classes.backgroundModal : null} /> <div className={shareOpen ? classes.backgroundModal : null} />
<Button onClick={_handleClose}> <Button onClick={_handleClose}>
@@ -45,7 +45,7 @@ InjectDebugData([
{ {
id: 3, id: 3,
display: 'Chip', display: 'Chip',
number: '417-8792', number: '777-7777',
}, },
], ],
}, },
@@ -1,4 +1,4 @@
import React, { useState } from 'react'; import React, { useEffect, useState } from 'react';
import { import {
Avatar as MuiAvatar, Avatar as MuiAvatar,
Box, Box,
@@ -13,12 +13,18 @@ import { useContacts } from '../../hooks/useContacts';
import Nui from '../../../../os/nui-events/utils/Nui'; import Nui from '../../../../os/nui-events/utils/Nui';
import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import LogDebugEvent from '../../../../os/debug/LogDebugEvents'; import LogDebugEvent from '../../../../os/debug/LogDebugEvents';
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
interface ContactInfoRouteParams { interface ContactInfoRouteParams {
mode: string; mode: string;
id: string; id: string;
} }
interface ContactInfoRouteQuery {
addNumber?: string;
referal?: string;
}
const useStyles = makeStyles((theme: Theme) => ({ const useStyles = makeStyles((theme: Theme) => ({
root: { root: {
height: '100%', height: '100%',
@@ -54,6 +60,7 @@ const ContactsInfoPage = () => {
const { getContact } = useContacts(); const { getContact } = useContacts();
const { id } = useParams<ContactInfoRouteParams>(); const { id } = useParams<ContactInfoRouteParams>();
const { addNumber, referal } = useQueryParams<ContactInfoRouteQuery>({ referal: '/contacts' });
const contact = getContact(parseInt(id)); const contact = getContact(parseInt(id));
@@ -64,6 +71,12 @@ const ContactsInfoPage = () => {
const { t } = useTranslation(); const { t } = useTranslation();
useEffect(() => {
if (addNumber) {
setNumber(addNumber);
}
}, [addNumber]);
const handleContactAdd = () => { const handleContactAdd = () => {
LogDebugEvent({ LogDebugEvent({
action: 'Handling Contact Add', action: 'Handling Contact Add',
@@ -75,7 +88,7 @@ const ContactsInfoPage = () => {
number, number,
avatar, avatar,
}); });
history.goBack(); history.replace(referal);
}; };
const handleContactSave = () => { const handleContactSave = () => {
@@ -113,6 +126,7 @@ const ContactsInfoPage = () => {
<div className={classes.listContainer}> <div className={classes.listContainer}>
<MuiAvatar className={classes.avatar} src={avatar} /> <MuiAvatar className={classes.avatar} src={avatar} />
<TextField <TextField
autoFocus
className={classes.input} className={classes.input}
value={name} value={name}
onChange={(e) => setName(e.target.value)} onChange={(e) => setName(e.target.value)}
@@ -4,7 +4,7 @@ import { makeStyles, Theme } from '@material-ui/core/styles';
const useStyles = makeStyles((theme: Theme) => ({ const useStyles = makeStyles((theme: Theme) => ({
root: { root: {
backgroundColor: '#e9e9e9', backgroundColor: theme.palette.background.default,
}, },
})); }));
+26 -23
View File
@@ -10,6 +10,32 @@ import DialerNavBar from './DialerNavBar';
import { useDialHistory } from '../hooks/useDialHistory'; import { useDialHistory } from '../hooks/useDialHistory';
import InjectDebugData from '../../../os/debug/InjectDebugData'; import InjectDebugData from '../../../os/debug/InjectDebugData';
import { ContactList } from '../../contacts/components/List/ContactList'; import { ContactList } from '../../contacts/components/List/ContactList';
import { DialerThemeProvider } from '../providers/DialerThemeProvider';
export const DialerApp = () => {
const history = useDialHistory();
const dialer = useApp('DIALER');
return (
<DialerThemeProvider>
<AppWrapper>
<AppTitle app={dialer} />
<AppContent>
<Switch>
<Route path='/phone/dial'>
<DialPage />
</Route>
<Route exact path='/phone'>
<DialerHistory calls={history} />
</Route>
<Route path='/phone/contacts' component={ContactList}></Route>
</Switch>
</AppContent>
<DialerNavBar />
</AppWrapper>
</DialerThemeProvider>
);
};
InjectDebugData([ InjectDebugData([
{ {
@@ -29,26 +55,3 @@ InjectDebugData([
], ],
}, },
]); ]);
export const DialerApp = () => {
const history = useDialHistory();
const dialer = useApp('DIALER');
return (
<AppWrapper>
<AppTitle app={dialer} />
<AppContent>
<Switch>
<Route path='/phone/dial'>
<DialPage />
</Route>
<Route exact path='/phone'>
<DialerHistory calls={history} />
</Route>
<Route path='/phone/contacts' component={ContactList}></Route>
</Switch>
</AppContent>
<DialerNavBar />
</AppWrapper>
);
};
@@ -2,8 +2,10 @@ import React, { useContext } from 'react';
import { Box, IconButton, InputBase, Paper } from '@material-ui/core'; import { Box, IconButton, InputBase, Paper } from '@material-ui/core';
import { makeStyles, Theme } from '@material-ui/core/styles'; import { makeStyles, Theme } from '@material-ui/core/styles';
import PhoneIcon from '@material-ui/icons/Phone'; import PhoneIcon from '@material-ui/icons/Phone';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import { DialInputCtx } from '../context/InputContext'; import { DialInputCtx } from '../context/InputContext';
import Nui from '../../../os/nui-events/utils/Nui'; import Nui from '../../../os/nui-events/utils/Nui';
import { useHistory } from 'react-router-dom';
const useStyles = makeStyles((theme: Theme) => ({ const useStyles = makeStyles((theme: Theme) => ({
root: { root: {
@@ -26,8 +28,9 @@ const useStyles = makeStyles((theme: Theme) => ({
export const DialerInput = () => { export const DialerInput = () => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory();
const { inputVal } = useContext(DialInputCtx) const { inputVal } = useContext(DialInputCtx);
const handleCall = (number: string) => { const handleCall = (number: string) => {
Nui.send('phone:beginCall', { Nui.send('phone:beginCall', {
@@ -35,6 +38,10 @@ export const DialerInput = () => {
}); });
}; };
const handleNewContact = (number: string) => {
history.push(`/contacts/-1/?addNumber=${number}&referal=/phone/contacts`)
}
return ( return (
<Box component={Paper} className={classes.root}> <Box component={Paper} className={classes.root}>
<InputBase <InputBase
@@ -42,8 +49,11 @@ export const DialerInput = () => {
className={classes.input} className={classes.input}
value={inputVal} value={inputVal}
/> />
<IconButton color='primary' className={classes.iconBtn}>
<PhoneIcon fontSize="large" onClick={() => handleCall(inputVal)} />
</IconButton>
<IconButton className={classes.iconBtn}> <IconButton className={classes.iconBtn}>
<PhoneIcon onClick={() => handleCall(inputVal)} /> <PersonAddIcon fontSize="large" onClick={() => handleNewContact(inputVal)} />
</IconButton> </IconButton>
</Box> </Box>
); );
@@ -9,10 +9,10 @@ import HistoryIcon from '@material-ui/icons/History';
const useStyles = makeStyles((theme: Theme) => ({ const useStyles = makeStyles((theme: Theme) => ({
root: { root: {
width: '100%', width: '100%',
backgroundColor: theme.palette.background.default, backgroundColor: theme.palette.background.paper,
}, },
icon: { icon: {
color: '#43a047', color: theme.palette.primary.main,
}, },
})); }));
@@ -1,7 +1,8 @@
import React from 'react'; import React from 'react';
import ListItemText from '@material-ui/core/ListItemText';
import PhoneCallbackIcon from '@material-ui/icons/PhoneCallback'; import PhoneCallbackIcon from '@material-ui/icons/PhoneCallback';
import PhoneForwardedIcon from '@material-ui/icons/PhoneForwarded'; import PhoneForwardedIcon from '@material-ui/icons/PhoneForwarded';
import PhoneIcon from '@material-ui/icons/Phone';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import { List } from '../../../../ui/components/List'; import { List } from '../../../../ui/components/List';
import { ListItem } from '../../../../ui/components/ListItem'; import { ListItem } from '../../../../ui/components/ListItem';
import Nui from '../../../../os/nui-events/utils/Nui'; import Nui from '../../../../os/nui-events/utils/Nui';
@@ -10,11 +11,27 @@ import { useContacts } from '../../../contacts/hooks/useContacts';
import { ICall } from '../../../../common/typings/call'; import { ICall } from '../../../../common/typings/call';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Box, IconButton, ListItemIcon, ListItemText } from '@material-ui/core';
import { useHistory } from 'react-router-dom';
import { makeStyles, Theme } from '@material-ui/core/styles';
const useStyles = makeStyles((theme: Theme) => ({
callForward: {
color: theme.palette.success.main,
},
callBack: {
color: theme.palette.error.main,
},
}));
export const DialerHistory = ({ calls }) => { export const DialerHistory = ({ calls }) => {
const { number } = useSimcard(); const { number } = useSimcard();
const { getDisplayByNumber } = useContacts(); const { getDisplayByNumber } = useContacts();
const classes = useStyles();
const history = useHistory();
const { t } = useTranslation(); const { t } = useTranslation();
const handleCall = (phoneNumber) => { const handleCall = (phoneNumber) => {
@@ -23,8 +40,22 @@ export const DialerHistory = ({ calls }) => {
}); });
}; };
if (!calls) { if (!calls?.length) {
return <p>Things are loading or arent here at all</p>; return (
<Box
display='flex'
justifyContent='center'
alignItems='center'
paddingTop={35}
>
<p>
You got no friends!
<span role='img' aria-label='deal with it'>
😎
</span>
</p>
</Box>
);
} }
return ( return (
@@ -34,27 +65,59 @@ export const DialerHistory = ({ calls }) => {
<ListItem <ListItem
key={call.id} key={call.id}
divider divider
button
onClick={() => handleCall(call.receiver)}
> >
<ListItemIcon>
{<PhoneForwardedIcon className={classes.callForward} />}
</ListItemIcon>
<ListItemText <ListItemText
primary={getDisplayByNumber(call.receiver)} primary={getDisplayByNumber(call.receiver)}
secondary={new Date(call.start).getUTCDate()} secondary={dayjs.unix(call.start).format(t('DATE_TIME_FORMAT'))}
/> />
{<PhoneForwardedIcon />} <IconButton onClick={() => handleCall(call.receiver)}>
{<PhoneIcon />}
</IconButton>
{getDisplayByNumber(call.transmitter) === call.transmitter ? (
<IconButton
onClick={() =>
history.push(
`/contacts/-1?addNumber=${call.transmitter}&referal=/phone/contacts`
)
}
>
{<PersonAddIcon />}
</IconButton>
) : null}
</ListItem> </ListItem>
) : ( ) : (
<ListItem <ListItem
key={call.id} key={call.id}
divider divider
button
onClick={() => handleCall(call.transmitter)}
> >
<ListItemIcon>
{<PhoneCallbackIcon className={classes.callBack} />}
</ListItemIcon>
<ListItemText <ListItemText
primary={getDisplayByNumber(call.transmitter)} primary={getDisplayByNumber(call.transmitter)}
secondary={dayjs.unix(call.start).format(t('DATE_TIME_FORMAT'))} secondary={dayjs.unix(call.start).format(t('DATE_TIME_FORMAT'))}
/> />
{<PhoneCallbackIcon />} <IconButton onClick={() => handleCall(call.transmitter)}>
{<PhoneIcon />}
</IconButton>
{getDisplayByNumber(call.transmitter) === call.transmitter ? (
<IconButton
onClick={() =>
history.push(
`/contacts/-1?addNumber=${call.transmitter}&referal=/phone/contacts`
)
}
>
{<PersonAddIcon />}
</IconButton>
) : null}
</ListItem> </ListItem>
) )
)} )}
+17
View File
@@ -0,0 +1,17 @@
import { common, green } from "@material-ui/core/colors";
export const DIALER_APP_PRIMARY_COLOR = green[600];
export const DIALER_APP_TEXT_COLOR = common.white;
const theme = {
palette: {
primary: {
main: DIALER_APP_PRIMARY_COLOR,
dark: green[800],
light: green[400],
contrastText: DIALER_APP_TEXT_COLOR
}
}
}
export default theme;
+1 -1
View File
@@ -3,6 +3,6 @@ import { atom } from 'recoil';
export const dialState = { export const dialState = {
history: atom({ history: atom({
key: 'dialHistory', key: 'dialHistory',
default: null, default: [],
}), }),
}; };
@@ -5,7 +5,7 @@ interface ICallUI {
history: ICall[]; history: ICall[];
} }
export const useDialHistory = (): ICallUI => { export const useDialHistory = (): ICallUI[] => {
const history = useRecoilValue(dialState.history); const history = useRecoilValue(dialState.history);
return history; return history;
}; };
@@ -0,0 +1,4 @@
import { createAppThemeProvider } from '../../../os/apps/utils/createAppThemeProvider';
import dialerTheme from '../dialer.theme';
export const DialerThemeProvider = createAppThemeProvider(dialerTheme);
@@ -1,4 +1,4 @@
import React from 'react'; import React, { useState } from 'react';
import { AppWrapper } from '../../../ui/components'; import { AppWrapper } from '../../../ui/components';
import { AppContent } from '../../../ui/components/AppContent'; import { AppContent } from '../../../ui/components/AppContent';
@@ -6,12 +6,17 @@ import { useApp } from '../../../os/apps/hooks/useApps';
import { useExample } from '../hooks/useExample'; import { useExample } from '../hooks/useExample';
import { ExampleThemeProvider } from '../providers/ExampleThemeProvider'; import { ExampleThemeProvider } from '../providers/ExampleThemeProvider';
import { AppTitle } from '../../../ui/components/AppTitle'; import { AppTitle } from '../../../ui/components/AppTitle';
import { Button } from '@material-ui/core'; import PlayIcon from '@material-ui/icons/PlayArrow';
import StopIcon from '@material-ui/icons/Stop';
import { Button, IconButton } from '@material-ui/core';
import useSound from '../../../os/phone/hooks/useSound';
export const ExampleApp = () => { export const ExampleApp = () => {
// calling the example hook, and we assign the value to a variable // calling the example hook, and we assign the value to a variable
const exampleString = useExample(); const exampleString = useExample();
const example = useApp('EXAMPLE'); const example = useApp('EXAMPLE');
const [soundName, setSound] = useState('pixel.ogg');
const { play, playing, stop } = useSound('media/ringtones/' + soundName);
return ( return (
<ExampleThemeProvider> <ExampleThemeProvider>
<AppWrapper> <AppWrapper>
@@ -21,6 +26,12 @@ export const ExampleApp = () => {
<Button color='primary'>{example.id}</Button> <Button color='primary'>{example.id}</Button>
{/* Here we are using the value in a h3 tag */} {/* Here we are using the value in a h3 tag */}
<h3>{exampleString}</h3> <h3>{exampleString}</h3>
<IconButton onClick={() => (playing ? stop() : play())}>
{playing ? <StopIcon /> : <PlayIcon />}
</IconButton>
<Button onClick={() => setSound('marimba.ogg')}>
Change sound on the fly
</Button>
</AppContent> </AppContent>
</AppWrapper> </AppWrapper>
</ExampleThemeProvider> </ExampleThemeProvider>
+2 -2
View File
@@ -8,8 +8,8 @@ export const HomeApp = () => {
const { apps } = useApps(); const { apps } = useApps();
return ( return (
<AppWrapper> <AppWrapper>
<Box width='100%' mt={6} px={1}> <Box component="div" mt={6} px={1}>
{apps && <GridMenu items={apps} />} {apps && <GridMenu xs={3} items={apps} />}
</Box> </Box>
</AppWrapper> </AppWrapper>
); );
@@ -12,9 +12,11 @@ const useStyles = makeStyles((theme) => ({
mySms: { mySms: {
float: 'right', float: 'right',
margin: theme.spacing(1), margin: theme.spacing(1),
padding: '6px 12px', padding: '6px 16px',
height: 'auto', height: 'auto',
width: '80%', width: 'auto',
minWidth: '60%',
maxWidth: '85%',
background: theme.palette.background.default, background: theme.palette.background.default,
color: theme.palette.text.primary, color: theme.palette.text.primary,
borderRadius: '20px', borderRadius: '20px',
@@ -24,7 +26,9 @@ const useStyles = makeStyles((theme) => ({
float: 'left', float: 'left',
margin: theme.spacing(1), margin: theme.spacing(1),
padding: '6px 12px', padding: '6px 12px',
width: '80%', width: 'auto',
minWidth: '60%',
maxWidth: '85%',
height: 'auto', height: 'auto',
background: theme.palette.primary.light, background: theme.palette.primary.light,
color: theme.palette.getContrastText(theme.palette.primary.light), color: theme.palette.getContrastText(theme.palette.primary.light),
@@ -62,7 +66,7 @@ export const MessageBubble = ({
<div>{message.message}</div> <div>{message.message}</div>
)} )}
</Box> </Box>
<Box textAlign='right'> <Box>
<Typography variant='subtitle1' color='secondary'> <Typography variant='subtitle1' color='secondary'>
{isGroupChat && !message.isMine {isGroupChat && !message.isMine
? message.display || message.phone_number ? message.display || message.phone_number
-7
View File
@@ -1,7 +0,0 @@
#notes-app .Mui-focused::after {
border-bottom: 3px solid #f9a825;
}
#notes-app .MuiOutlinedInput-root {
border: 2px soild #f9a825;
}
+33 -39
View File
@@ -4,17 +4,45 @@ import { AppContent } from '../../ui/components/AppContent';
import { AppTitle } from '../../ui/components/AppTitle'; import { AppTitle } from '../../ui/components/AppTitle';
import { useApp } from '../../os/apps/hooks/useApps'; import { useApp } from '../../os/apps/hooks/useApps';
import NoteList from './list/NoteList'; import NoteList from './list/NoteList';
import { useNotes } from './hooks/useNotes';
import { NoteModal } from './modal/NoteModal'; import { NoteModal } from './modal/NoteModal';
import { Fab } from '@material-ui/core'; import { Fab } from '@material-ui/core';
import AddIcon from '@material-ui/icons/Add'; import AddIcon from '@material-ui/icons/Add';
import { useNoteModal } from './hooks/useNoteModal';
import { useNoteDetail } from './hooks/useNoteDetail'; import { useNoteDetail } from './hooks/useNoteDetail';
import useStyles from './notes.styles'; import useStyles from './notes.styles';
import InjectDebugData from '../../os/debug/InjectDebugData'; import InjectDebugData from '../../os/debug/InjectDebugData';
import { NotesThemeProvider } from './providers/NotesThemeProvider';
import { Route, useHistory } from 'react-router-dom';
export const NotesApp = () => {
const classes = useStyles();
const history = useHistory();
const notesApp = useApp('NOTES');
const { setDetail } = useNoteDetail();
const onClickCreate = () => {
setDetail({ title: '', content: '' });
history.push('/notes/detail');
};
return (
<NotesThemeProvider>
<AppWrapper id='notes-app'>
<AppTitle app={notesApp} />
<Route path='/notes/detail' component={NoteModal} />
<AppContent>
<Route path='/notes' component={NoteList} />
<Fab
className={classes.absolute}
onClick={onClickCreate}
color='primary'
>
<AddIcon />
</Fab>
</AppContent>
</AppWrapper>
</NotesThemeProvider>
);
};
InjectDebugData([ InjectDebugData([
{ {
@@ -34,37 +62,3 @@ InjectDebugData([
], ],
}, },
]); ]);
export const NotesApp = () => {
const { setNoteModal } = useNoteModal();
const { detail, setDetail } = useNoteDetail();
const { notes } = useNotes();
const notesApp = useApp('NOTES');
const classes = useStyles();
const handleModal = () => {
setNoteModal(true);
setDetail(null);
};
return (
<AppWrapper id='notes-app'>
<AppTitle app={notesApp} />
<NoteModal key={detail?.id} />
<AppContent>
<NoteList notes={notes} />
</AppContent>
<Fab
className={classes.absolute}
onClick={handleModal}
style={{
background: '#f9a825',
color: '#fff',
}}
>
<AddIcon />
</Fab>
</AppWrapper>
);
};
+18 -6
View File
@@ -1,18 +1,30 @@
import React from 'react'; import React from 'react';
import { yellow } from '@material-ui/core/colors'; import { makeStyles, Paper } from '@material-ui/core';
import useStyles from './notes.styles';
import { Paper } from '@material-ui/core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faStickyNote } from '@fortawesome/free-solid-svg-icons'; import { faStickyNote } from '@fortawesome/free-solid-svg-icons';
const useStyles = makeStyles((theme) => ({
header: {
width: '100%',
display: 'flex',
flexFlow: 'row nowrap',
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
height: '60px',
},
icon: {
color: theme.palette.primary.main,
fontSize: 40,
},
}));
const NotesTitle = () => { const NotesTitle = () => {
const classes = useStyles(); const classes = useStyles();
return ( return (
<Paper elevation={24} square variant='outlined' className={classes.header}> <Paper elevation={24} square variant='outlined' className={classes.header}>
<FontAwesomeIcon icon={faStickyNote} color={yellow[800]} size='lg' /> <FontAwesomeIcon icon={faStickyNote} className={classes.icon} size='lg' />
</Paper> </Paper>
); );
}; };
@@ -1,12 +0,0 @@
import { useRecoilState } from 'recoil';
import { noteStates } from './state';
interface NoteModalProps {
noteModal: boolean;
setNoteModal: (show: boolean) => void;
}
export const useNoteModal = (): NoteModalProps => {
const [noteModal, setNoteModal] = useRecoilState(noteStates.noteModal);
return { noteModal, setNoteModal };
};
+7 -6
View File
@@ -1,18 +1,19 @@
import { List, ListItem, ListItemText } from '@material-ui/core';
import React from 'react'; import React from 'react';
import { List, ListItem, ListItemText } from '@material-ui/core';
import { useNoteModal } from '../hooks/useNoteModal';
import { useNoteDetail } from '../hooks/useNoteDetail'; import { useNoteDetail } from '../hooks/useNoteDetail';
import { useNotes } from '../hooks/useNotes';
import { useHistory } from 'react-router-dom';
// add search bar later // add search bar later
// TODO: Add interface for note // TODO: Add interface for note
const NoteList = ({ notes }) => { const NoteList = () => {
const { setNoteModal } = useNoteModal(); const history = useHistory();
const { notes } = useNotes();
const { setDetail } = useNoteDetail(); const { setDetail } = useNoteDetail();
const handleNoteModal = (note) => { const handleNoteModal = (note) => {
setNoteModal(true);
setDetail(note); setDetail(note);
history.push('/notes/detail');
}; };
return ( return (
+121 -89
View File
@@ -1,41 +1,39 @@
import { Button, TextField, Slide } from '@material-ui/core'; import {
import React, { useState } from 'react'; Button,
TextField,
Slide,
Paper,
Typography,
Container,
CircularProgress,
Box,
} from '@material-ui/core';
import React from 'react';
import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import { useNoteModal } from '../hooks/useNoteModal';
import { useNoteDetail } from '../hooks/useNoteDetail'; import { useNoteDetail } from '../hooks/useNoteDetail';
import useStyles from './modal.styles'; import useStyles from './modal.styles';
import '../NotesApp.css';
import Nui from '../../../os/nui-events/utils/Nui'; import Nui from '../../../os/nui-events/utils/Nui';
import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router-dom';
import { StatusButton } from '../../../ui/components/StatusButton';
// TODO: Fix input focus color
export const NoteModal = () => { export const NoteModal = () => {
const { noteModal, setNoteModal } = useNoteModal(); const classes = useStyles();
const history = useHistory();
const { t } = useTranslation();
const { detail, setDetail } = useNoteDetail(); const { detail, setDetail } = useNoteDetail();
const [title, setTitle] = useState(detail ? detail.title : '');
const [content, setContent] = useState(detail ? detail.content : '');
const classes = useStyles()
const onClose = () => history.goBack();
const _handleClose = () => { const _handleClose = () => {
setDetail(null); setDetail(null);
setNoteModal(false); onClose();
}; };
const handleNoteSave = () => { const handleNoteSave = () => {
Nui.send('phone:addNote', { Nui.send('phone:addNote', detail);
title,
content,
});
setDetail(null); setDetail(null);
setNoteModal(false); onClose();
setTitle('')
setContent('')
}; };
const handleDeleteNote = () => { const handleDeleteNote = () => {
@@ -44,78 +42,112 @@ export const NoteModal = () => {
id, id,
}); });
setDetail(null); setDetail(null);
setNoteModal(false); onClose();
}; };
const handleUpdateNote = () => { const handleUpdateNote = () => {
Nui.send('phone:updateNote', { Nui.send('phone:updateNote', detail);
id: detail.id,
title,
content,
});
setDetail(null); setDetail(null);
setNoteModal(false); onClose();
}; };
return ( return (
<div className={noteModal ? classes.modalRoot : classes.modalHide}> <Slide direction='left' in={!!detail}>
<Slide direction='left' in={noteModal} mountOnEnter unmountOnExit> <Paper className={classes.modalRoot}>
<div> {!detail ? (
<Button className={classes.closeButton} onClick={_handleClose}> <CircularProgress />
<ArrowBackIcon fontSize='large' /> ) : (
</Button> <Container>
<div id='notes-modal' className={classes.noteContainer}> <Box>
<TextField <Box py={2}>
className={classes.input} <Button
rowsMax={1} color='primary'
placeholder='Title' size='large'
inputProps={{ startIcon={<ArrowBackIcon fontSize='large' />}
className: classes.inputPropsTitle, onClick={_handleClose}
maxLength: 25 >
}} {t('APPS_NOTES')}
fullWidth </Button>
value={title} </Box>
onChange={(e) => setTitle(e.target.value)} <TextField
/> className={classes.input}
<TextField rowsMax={1}
className={classes.input} label={t('GENERIC_TITLE')}
inputProps={{ inputProps={{
className: classes.inputPropsContent, className: classes.inputPropsTitle,
maxLength: 250, maxLength: 25,
}} }}
placeholder='Content' fullWidth
multiline value={detail.title}
fullWidth onChange={(e) =>
rows={19} setDetail((d) => ({ ...d, title: e.target.value }))
variant='outlined' }
value={content} />
onChange={(e) => setContent(e.target.value)} <TextField
/> className={classes.input}
<p style={{ color: "#fff" }}>{content.length}/250</p> inputProps={{
{!detail &&( className: classes.inputPropsContent,
<Button disabled={title.length > 0 ? false : true} className={classes.saveButton} onClick={handleNoteSave}> maxLength: 250,
Save }}
</Button> label={t('GENERIC_CONTENT')}
)} multiline
{detail && ( fullWidth
<Button rows={16}
className={classes.updateButton} variant='outlined'
onClick={handleUpdateNote} value={detail.content}
> onChange={(e) =>
Update setDetail((d) => ({ ...d, content: e.target.value }))
</Button> }
)} />
{detail && ( <Typography paragraph>{detail.content.length}/250</Typography>
<Button {!detail.id ? (
className={classes.deleteButton} <>
onClick={handleDeleteNote} <Box display="inline" p={1}>
> <Button
Delete color='primary'
</Button> variant='contained'
)} disabled={detail.title.length > 0 ? false : true}
</div> onClick={handleNoteSave}
</div> >
</Slide> {t('GENERIC_SAVE')}
</div> </Button>
</Box>
<Box display="inline" p={1}>
<StatusButton
color='error'
variant='contained'
onClick={_handleClose}
>
{t('GENERIC_CANCEL')}
</StatusButton>
</Box>
</>
) : (
<>
<Box display="inline" p={1}>
<Button
color='primary'
variant='contained'
onClick={handleUpdateNote}
>
{t('GENERIC_UPDATE')}
</Button>
</Box>
<Box display="inline" p={1}>
<StatusButton
color='error'
variant='contained'
onClick={handleDeleteNote}
>
{t('GENERIC_DELETE')}
</StatusButton>
</Box>
</>
)}
</Box>
</Container>
)}
</Paper>
</Slide>
); );
}; };
+3 -29
View File
@@ -4,23 +4,9 @@ const useStyles = makeStyles((theme) => ({
modalRoot: { modalRoot: {
zIndex: 20, zIndex: 20,
position: 'absolute', position: 'absolute',
height: '100%', height: '99%',
width: '100%', width: '100%',
background: '#232323', background: theme.palette.background.default,
},
modalHide: {
display: 'none',
},
closeButton: {
width: '10%',
position: 'absolute',
top: 10,
left: 0,
},
noteContainer: {
width: '90%',
marginTop: 80,
margin: '0 auto',
}, },
input: { input: {
marginBottom: 20, marginBottom: 20,
@@ -30,19 +16,7 @@ const useStyles = makeStyles((theme) => ({
}, },
inputPropsContent: { inputPropsContent: {
fontSize: 20, fontSize: 20,
}, lineHeight: 1.2,
saveButton: {
background: '#f9a825',
padding: '10px 30px',
},
updateButton: {
background: '#f9a825',
padding: '10px 30px',
marginRight: '8px',
},
deleteButton: {
background: '#c62828',
padding: '10px 30px',
}, },
})); }));
-9
View File
@@ -1,15 +1,6 @@
import { makeStyles } from '@material-ui/core'; import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({ const useStyles = makeStyles((theme) => ({
header: {
width: '100%',
display: 'flex',
flexFlow: 'row nowrap',
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
height: '60px',
},
backgroundModal: { backgroundModal: {
background: 'black', background: 'black',
opacity: '0.6', opacity: '0.6',
+18
View File
@@ -0,0 +1,18 @@
import { common, yellow } from "@material-ui/core/colors";
export const NOTES_APP_PRIMARY_COLOR = yellow[800];
export const NOTES_APP_ICON_COLOR = common.white;
export const NOTES_APP_TEXT_COLOR = common.black;
const theme = {
palette: {
primary: {
main: NOTES_APP_PRIMARY_COLOR,
dark: yellow[900],
light: yellow[500],
contrastText: NOTES_APP_TEXT_COLOR
}
}
}
export default theme;
@@ -0,0 +1,4 @@
import { createAppThemeProvider } from "../../../os/apps/utils/createAppThemeProvider";
import notesTheme from '../notes.theme';
export const NotesThemeProvider = createAppThemeProvider(notesTheme);
+9 -5
View File
@@ -1,12 +1,16 @@
import { common } from "@material-ui/core/colors"; import { common, red } from "@material-ui/core/colors";
export const SELLOUT_APP_PRIMARY_COLOR = red[500];
export const SELLOUT_APP_ICON_COLOR = common.white;
export const SELLOUT_APP_TEXT_COLOR = common.black;
const theme = { const theme = {
palette: { palette: {
primary: { primary: {
main: '#f44336', main: SELLOUT_APP_PRIMARY_COLOR,
dark: '#b3251b', dark: red[700],
light: 'f87f76', light: red[200],
contrastText: common.black contrastText: SELLOUT_APP_TEXT_COLOR
} }
} }
} }
+100 -94
View File
@@ -20,100 +20,6 @@ import { useProfile } from '../hooks/useProfile';
import ProfilePrompt from './profile/ProfilePrompt'; import ProfilePrompt from './profile/ProfilePrompt';
import InjectDebugData from '../../../os/debug/InjectDebugData'; import InjectDebugData from '../../../os/debug/InjectDebugData';
InjectDebugData([
{
app: 'TWITTER',
method: 'getOrCreateTwitterProfile',
data: {
profile_name: 'Angular_Dev',
bio: 'Angular FTW',
job: 'Googler @ Google',
location: '1600 Amphitheatre Parkway, CA, USA',
avatar_url: 'https://i.tasoagc.dev/i9Ig',
},
},
{
app: 'TWITTER',
method: 'createTweetBroadcast',
data: {
id: 111,
profile_id: 111,
profile_name: 'Kidz',
isMine: false,
isReported: false,
message: 'I have tweeted this because Im badass'
}
},
{
app: 'TWITTER',
method: 'createTweetBroadcast',
data: {
id: 111,
profile_id: 111,
profile_name: 'ItsChip',
isMine: false,
isReported: false,
message: 'I have tweeted this because Im even more badass'
}
},
{
app: 'TWITTER',
method: 'fetchTweets',
data: [
{
id: 59,
message: 'XSS\n<script src="test.js">Test</script>\nBro',
avatar_url: 'http://i.tasoagc.dev/jtKL',
seconds_since_tweet: 500,
isMine: false,
updateAt: '2021-02-08 14:37:46',
visible: 1,
likes: 50000,
profile_name: 'jQuery Main',
images: 'http://i.tasoagc.dev/0xdp',
},
{
id: 2,
message: 'GCPhone will never die',
avatar_url: 'http://i.tasoagc.dev/jtKL',
seconds_since_tweet: 500,
isMine: false,
updateAt: '2021-02-08 14:37:46',
visible: 1,
likes: 50000,
profile_name: 'GCPhone_v9999',
images: 'http://i.tasoagc.dev/0xdp',
},
{
id: 1,
message: 'I love angular',
avatar_url: 'https://i.tasoagc.dev/i9Ig',
seconds_since_tweet: 800,
isMine: true,
updateAt: '2021-02-08 14:37:46',
visible: 1,
likes: 50000,
profile_name: 'Angular_Dev',
images: 'http://i.tasoagc.dev/i9Ig',
},
{
id: 3,
message:
'Anyways uhm... I bought a whole bunch of shungite, rocks, ' +
'do you know what shungite is? Anybody know what shungite is. No, no ' +
'Suge Knight, I think hes locked up in prison.',
avatar_url: 'http://i.tasoagc.dev/0v64',
seconds_since_tweet: 800,
isMine: true,
updateAt: '2021-02-08 14:37:46',
visible: 1,
likes: 50000,
profile_name: 'The_Doc',
},
],
},
]);
const useStyles = makeStyles(() => ({ const useStyles = makeStyles(() => ({
backgroundModal: { backgroundModal: {
background: 'black', background: 'black',
@@ -186,3 +92,103 @@ export const TwitterApp = () => {
</AppWrapper> </AppWrapper>
); );
}; };
InjectDebugData([
{
app: 'TWITTER',
method: 'getOrCreateTwitterProfile',
data: {
profile_name: 'Angular_Dev',
bio: 'Angular FTW',
job: 'Googler @ Google',
location: '1600 Amphitheatre Parkway, CA, USA',
avatar_url: 'https://i.tasoagc.dev/i9Ig',
},
},
{
app: 'TWITTER',
method: 'fetchTweets',
data: [
{
id: 59,
message: 'XSS\n<script src="test.js">Test</script>\nBro',
avatar_url: 'http://i.tasoagc.dev/jtKL',
seconds_since_tweet: 500,
isMine: false,
updateAt: '2021-02-08 14:37:46',
visible: 1,
likes: 50000,
profile_name: 'jQuery Main',
images: 'http://i.tasoagc.dev/0xdp',
},
{
id: 2,
message: 'GCPhone will never die',
avatar_url: 'http://i.tasoagc.dev/jtKL',
seconds_since_tweet: 500,
isMine: false,
updateAt: '2021-02-08 14:37:46',
visible: 1,
likes: 50000,
profile_name: 'GCPhone_v9999',
images: 'http://i.tasoagc.dev/0xdp',
},
{
id: 1,
message: 'I love angular',
avatar_url: 'https://i.tasoagc.dev/i9Ig',
seconds_since_tweet: 800,
isMine: true,
updateAt: '2021-02-08 14:37:46',
visible: 1,
likes: 50000,
profile_name: 'Angular_Dev',
images: 'http://i.tasoagc.dev/i9Ig',
},
{
id: 3,
message:
'Anyways uhm... I bought a whole bunch of shungite, rocks, ' +
'do you know what shungite is? Anybody know what shungite is. No, no ' +
'Suge Knight, I think hes locked up in prison.',
avatar_url: 'http://i.tasoagc.dev/0v64',
seconds_since_tweet: 800,
isMine: true,
updateAt: '2021-02-08 14:37:46',
visible: 1,
likes: 50000,
profile_name: 'The_Doc',
},
],
},
]);
InjectDebugData(
[
{
app: 'TWITTER',
method: 'createTweetBroadcast',
data: {
id: 111,
profile_id: 111,
profile_name: 'Kidz',
isMine: false,
isReported: false,
message: 'I have tweeted this because Im badass',
},
},
{
app: 'TWITTER',
method: 'createTweetBroadcast',
data: {
id: 111,
profile_id: 111,
profile_name: 'ItsChip',
isMine: false,
isReported: false,
message: 'I have tweeted this because Im even more badass... And I need this to be longer so I will continue to write',
},
},
],
2000
);
@@ -2,15 +2,23 @@ import React, { useEffect } from 'react';
import Nui from '../../../../os/nui-events/utils/Nui'; import Nui from '../../../../os/nui-events/utils/Nui';
import { useTweets } from '../../hooks/useTweets'; import { useTweets } from '../../hooks/useTweets';
import { useTwitterNotifications } from '../../hooks/useTwitterNotifications';
import TweetList from './TweetList'; import TweetList from './TweetList';
export function TweetListContainer() { export function TweetListContainer() {
const { tweets } = useTweets(); const { tweets } = useTweets();
const { setUnreadCount } = useTwitterNotifications();
useEffect(() => { useEffect(() => {
Nui.send('phone:fetchTweets', {}); Nui.send('phone:fetchTweets', {});
}, []); }, []);
useEffect(() => {
if (tweets?.length) {
setUnreadCount(0);
}
}, [setUnreadCount, tweets]);
return <TweetList tweets={tweets} />; return <TweetList tweets={tweets} />;
} }
+3 -3
View File
@@ -37,8 +37,8 @@ export const twitterState = {
key: 'updateProfileSuccess', key: 'updateProfileSuccess',
default: null, default: null,
}), }),
notification: atom({ unreadTweetsCount: atom({
key: 'notification', key: 'unreadTweetsCount',
default: null, default: 0,
}), }),
}; };
@@ -1,13 +0,0 @@
import { useRecoilValue } from 'recoil';
import { Tweet } from '../../../common/typings/twitter';
import { twitterState } from './state';
interface ITwitterNotification {
notification: Tweet | null;
}
export const useTwitterNotification = (): ITwitterNotification => {
const notification = useRecoilValue<Tweet | null>(twitterState.notification);
return { notification };
};
@@ -0,0 +1,43 @@
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { useRecoilState } from "recoil";
import { useApp } from "../../../os/apps/hooks/useApps";
import { useNotifications } from "../../../os/notifications/hooks/useNotifications";
import { twitterState } from "./state";
export const useTwitterNotifications = () => {
const { t } = useTranslation();
const history = useHistory();
const { addNotificationAlert } = useNotifications();
const { icon, notificationIcon } = useApp('TWITTER');
const [unreadCount, setUnreadCount] = useRecoilState(twitterState.unreadTweetsCount);
const setNotification = useCallback(
({ profile_name, message }) => {
setUnreadCount((curr) => {
const unread = curr + 1;
addNotificationAlert(
{
app: 'TWITTER',
title: t('APPS_TWITTER_NEW_BROADCAST', { profile_name }),
onClick: () => history.push('/twitter'),
content: message,
icon,
notificationIcon,
},
true,
{
title: t('APPS_TWITTER_UNREAD_MESSAGES', {
count: unread,
}),
content: null,
}
);
return unread;
});
},
[setUnreadCount, addNotificationAlert, t, icon, notificationIcon, history]
);
return { setNotification, setUnreadCount, unreadCount }
};
@@ -5,11 +5,8 @@ import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
import { IMAGE_DELIMITER } from '../utils/images'; import { IMAGE_DELIMITER } from '../utils/images';
import { APP_TWITTER } from '../utils/constants'; import { APP_TWITTER } from '../utils/constants';
import { twitterState } from './state'; import { twitterState } from './state';
import { useNotifications } from '../../../os/notifications/hooks/useNotifications';
import { useApp } from '../../../os/apps/hooks/useApps';
import { useTranslation } from 'react-i18next';
import { useCallback } from 'react';
import { useSnackbar } from '../../../ui/hooks/useSnackbar'; import { useSnackbar } from '../../../ui/hooks/useSnackbar';
import { useTwitterNotifications } from './useTwitterNotifications';
/** /**
* Perform all necessary processing/transforms from the raw database * Perform all necessary processing/transforms from the raw database
@@ -33,23 +30,8 @@ function processTweet(tweet) {
* there and have moved that logic here instead. * there and have moved that logic here instead.
*/ */
export const useTwitterService = () => { export const useTwitterService = () => {
const { t } = useTranslation();
const { addNotification } = useNotifications();
const { addAlert } = useSnackbar() const { addAlert } = useSnackbar()
const { icon, notificationIcon } = useApp('TWITTER'); const { setNotification } = useTwitterNotifications();
const setNotification = useCallback(
({ profile_name, message }) =>
addNotification({
app: 'TWITTER',
title: t('APPS_TWITTER_NEW_BROADCAST', { profile_name }),
href: '/twitter',
content: message,
icon,
notificationIcon,
}),
[addNotification, icon, notificationIcon, t]
);
const setProfile = useSetRecoilState(twitterState.profile); const setProfile = useSetRecoilState(twitterState.profile);
const setUpdateProfileLoading = useSetRecoilState( const setUpdateProfileLoading = useSetRecoilState(
+8 -3
View File
@@ -10,7 +10,12 @@ import { useLocation } from 'react-router-dom';
* *
* const { id, title } = useQueryParams<{ id: string, title: string }>(); * const { id, title } = useQueryParams<{ id: string, title: string }>();
*/ */
export function useQueryParams<T = Record<string, string>>() { export function useQueryParams<T = Record<string, string>>(
return qs.parse(useLocation().search, { ignoreQueryPrefix: true }) as T & defaultValues: T = null
Partial<ParsedQs>; ) {
const query = qs.parse(useLocation().search, { ignoreQueryPrefix: true });
if (!defaultValues) {
return query as T & Partial<ParsedQs>;
}
return { ...defaultValues, ...query } as T & Partial<ParsedQs>;
} }
+1
View File
@@ -1,4 +1,5 @@
export interface CallProps { export interface CallProps {
active: boolean;
accepted: boolean; accepted: boolean;
isTransmitter: boolean; isTransmitter: boolean;
transmitter: string; transmitter: string;
+1 -1
View File
@@ -44,7 +44,7 @@
"palette": { "palette": {
"type": "dark", "type": "dark",
"primary": { "primary": {
"main": "#a6d4fa" "main": "#a6d4fa"
}, },
"background": { "background": {
"paper": "#1c1c1c", "paper": "#1c1c1c",
+2 -8
View File
@@ -6,10 +6,8 @@ import { RecoilRoot } from 'recoil';
import * as Sentry from '@sentry/react'; import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing'; import { Integrations } from '@sentry/tracing';
import './main.css'; import './main.css';
import Phone from './Phone';
import PhoneConfig from './config/default.json'; import PhoneConfig from './config/default.json';
import SnackbarProvider from './ui/providers/SnackbarProvider'; import { PhoneContainer } from './PhoneContainer';
import { NotificationsProvider } from './os/notifications/providers/NotificationsProvider';
// Enable Sentry when config setting is true // Enable Sentry when config setting is true
if (PhoneConfig.SentryErrorMetrics) { if (PhoneConfig.SentryErrorMetrics) {
@@ -27,11 +25,7 @@ if (PhoneConfig.SentryErrorMetrics) {
ReactDOM.render( ReactDOM.render(
<HashRouter> <HashRouter>
<RecoilRoot> <RecoilRoot>
<SnackbarProvider> <PhoneContainer />
<NotificationsProvider>
<Phone />
</NotificationsProvider>
</SnackbarProvider>
</RecoilRoot> </RecoilRoot>
</HashRouter>, </HashRouter>,
document.getElementById('root') document.getElementById('root')
+13 -1
View File
@@ -17,6 +17,14 @@
"APPS_SELLOUT": "Market", "APPS_SELLOUT": "Market",
"APPS_CAMERA": "Camera", "APPS_CAMERA": "Camera",
"APPS_DIALER_CURRENT_CALL_TITLE": "Current Phone Call",
"APPS_DIALER_INCOMING_CALL_TITLE": "Incoming Phone Call",
"APPS_DIALER_CURRENT_CALL_WITH": "In call with {{ transmitter }}",
"APPS_DIALER_TRANSMITTER_IS_CALLING": "{{ transmitter }} is calling you!",
"APPS_DIALER_ACCEPT_CALL": "Accept",
"APPS_DIALER_REJECT_CALL": "Reject",
"APPS_DIALER_END_CALL": "End",
"APPS_BANK_TRANSFER": "Transfer", "APPS_BANK_TRANSFER": "Transfer",
"APPS_SETTINGS_OPTIONS_WALLPAPER": "Wallpaper", "APPS_SETTINGS_OPTIONS_WALLPAPER": "Wallpaper",
"APPS_SETTINGS_OPTIONS_FRAME": "Frame", "APPS_SETTINGS_OPTIONS_FRAME": "Frame",
@@ -48,6 +56,7 @@
"APPS_TWITTER_TIME_HOURS": "h", "APPS_TWITTER_TIME_HOURS": "h",
"APPS_TWITTER_TIME_DAYS": "d", "APPS_TWITTER_TIME_DAYS": "d",
"APPS_TWITTER_NEW_BROADCAST": "New tweet from @{{ profile_name }}!", "APPS_TWITTER_NEW_BROADCAST": "New tweet from @{{ profile_name }}!",
"APPS_TWITTER_UNREAD_MESSAGES": "You have {{ count }} new tweets in your timeline!",
"APPS_BANK_HOME_TITLE": "Welcome", "APPS_BANK_HOME_TITLE": "Welcome",
"APPS_BANK_ACCOUNT_LINK": "Account", "APPS_BANK_ACCOUNT_LINK": "Account",
@@ -110,6 +119,9 @@
"GENERIC_SAVE": "Save", "GENERIC_SAVE": "Save",
"GENERIC_UPDATE": "Update", "GENERIC_UPDATE": "Update",
"GENERIC_DELETE": "Delete", "GENERIC_DELETE": "Delete",
"GENERIC_CLOSE": "Close" "GENERIC_CLOSE": "Close",
"GENERIC_CANCEL": "Cancel",
"GENERIC_TITLE": "Title",
"GENERIC_CONTENT": "Content"
} }
} }
-110
View File
@@ -1,110 +0,0 @@
import React from 'react';
import { Fab } from '@material-ui/core';
import { AppWrapper } from '../../ui/components/AppWrapper';
import { AppContent } from '../../ui/components/AppContent';
import { useCall } from '../hooks/useCall';
import CallIcon from '@material-ui/icons/Call';
import CallEndIcon from '@material-ui/icons/CallEnd';
import useStyles from './modal.styles';
import { useModal } from '../hooks/useModal';
import Nui from '../../os/nui-events/utils/Nui';
import CallTimer from './CallTimer';
import InjectDebugData from '../../os/debug/InjectDebugData';
InjectDebugData([
{
app: 'CALL',
method: 'setCaller',
data: {
accepted: true,
isTransmitter: true,
transmitter: 'Chip',
receiver: 'Taso',
phone_number: '860-4504',
},
},
]);
export const CallModal = () => {
const { call } = useCall();
const { setModal } = useModal();
const classes = useStyles();
const handleAcceptCall = () => {
Nui.send('phone:acceptCall', {
transmitterNumber: call.transmitter,
});
};
const handleRejectCall = () => {
setModal(false);
Nui.send('phone:rejectCall', {
phoneNumber: call.transmitter,
});
};
const handleEndCall = () => {
setModal(false);
Nui.send('phone:endCall', {
transmitterNumber: call.transmitter,
});
};
if (call.isTransmitter) {
return (
<AppWrapper>
<AppContent>
<h1 style={{ textAlign: 'center' }}>{call.receiver}</h1>
<CallTimer isAccepted={call.accepted} />
<div className={classes.actions}>
<Fab
onClick={handleEndCall}
style={{ backgroundColor: '#e74c3c', color: '#fff' }}
className={classes.actionButton}
>
<CallEndIcon />
</Fab>
</div>
</AppContent>
</AppWrapper>
);
}
return (
<AppWrapper>
<AppContent>
<h1 style={{ textAlign: 'center' }}>{call.transmitter}</h1>
<CallTimer isAccepted={call.accepted} />
<div className={classes.actions}>
{!call.accepted ? (
<>
<Fab
onClick={handleRejectCall}
style={{ backgroundColor: '#e74c3c', color: '#fff' }}
className={classes.actionButton}
>
<CallEndIcon />
</Fab>
<Fab
onClick={handleAcceptCall}
style={{ backgroundColor: '#27ae60', color: '#fff' }}
className={classes.actionButton}
>
<CallIcon />
</Fab>
</>
) : (
<Fab
onClick={handleEndCall}
style={{ backgroundColor: '#e74c3c', color: '#fff' }}
className={classes.actionButton}
>
<CallEndIcon />
</Fab>
)}
</div>
</AppContent>
</AppWrapper>
);
};
-13
View File
@@ -1,13 +0,0 @@
import { useRecoilState } from 'recoil';
import { CallProps } from '../../common/typings/call';
import { callerState } from './state';
interface CallHook {
call: CallProps;
setCall: (details: any) => void;
}
export const useCall = (): CallHook => {
const [call, setCall] = useRecoilState(callerState.currentCall);
return { call, setCall };
};
-11
View File
@@ -1,11 +0,0 @@
import { useNuiEvent } from '../../os/nui-events/hooks/useNuiEvent';
import { useRecoilState, useSetRecoilState } from 'recoil';
import { callerState } from './state';
export const useCallService = () => {
const [caller, setCaller] = useRecoilState(callerState.currentCall);
const setModal = useSetRecoilState(callerState.callModal);
useNuiEvent('CALL', 'setCaller', setCaller, {}, caller);
useNuiEvent('CALL', 'callModal', setModal);
};
+17 -16
View File
@@ -3,10 +3,7 @@ import {
blue, blue,
common, common,
grey, grey,
green,
purple, purple,
yellow,
red,
} from '@material-ui/core/colors'; } from '@material-ui/core/colors';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { import {
@@ -35,6 +32,7 @@ import { SelloutApp } from '../../../apps/sellout/components/SelloutApp';
import { NotesApp } from '../../../apps/notes/NotesApp'; import { NotesApp } from '../../../apps/notes/NotesApp';
import CameraApp from '../../../apps/camera/components/CameraApp'; import CameraApp from '../../../apps/camera/components/CameraApp';
import { AppRoute } from '../components/AppRoute'; import { AppRoute } from '../components/AppRoute';
import { import {
MESSAGES_APP_PRIMARY_COLOR, MESSAGES_APP_PRIMARY_COLOR,
MESSAGES_APP_TEXT_COLOR, MESSAGES_APP_TEXT_COLOR,
@@ -43,6 +41,9 @@ import {
CONTACTS_APP_PRIMARY_COLOR, CONTACTS_APP_PRIMARY_COLOR,
CONTACTS_APP_TEXT_COLOR, CONTACTS_APP_TEXT_COLOR,
} from '../../../apps/contacts/contacts.theme'; } from '../../../apps/contacts/contacts.theme';
import { SELLOUT_APP_PRIMARY_COLOR, SELLOUT_APP_ICON_COLOR } from '../../../apps/sellout/sellout.theme';
import { NOTES_APP_ICON_COLOR, NOTES_APP_PRIMARY_COLOR } from '../../../apps/notes/notes.theme';
import { DIALER_APP_PRIMARY_COLOR, DIALER_APP_TEXT_COLOR } from '../../../apps/dialer/dialer.theme';
export interface IAppConfig { export interface IAppConfig {
id: string; id: string;
@@ -59,17 +60,17 @@ export const APPS: IAppConfig[] = [
{ {
id: 'DIALER', id: 'DIALER',
nameLocale: 'APPS_DIALER', nameLocale: 'APPS_DIALER',
icon: <FontAwesomeIcon icon={faPhoneAlt} size='xs' />, icon: <FontAwesomeIcon icon={faPhoneAlt} />,
notificationIcon: <FontAwesomeIcon icon={faPhoneAlt} size='xs' />, notificationIcon: <FontAwesomeIcon icon={faPhoneAlt} size='xs' />,
backgroundColor: green[600], backgroundColor: DIALER_APP_PRIMARY_COLOR,
color: common.white, color: DIALER_APP_TEXT_COLOR,
path: '/phone', path: '/phone',
Route: () => <AppRoute id='DIALER' path='/phone' component={DialerApp} />, Route: () => <AppRoute id='DIALER' path='/phone' component={DialerApp} />,
}, },
{ {
id: 'MESSAGES', id: 'MESSAGES',
nameLocale: 'APPS_MESSAGES', nameLocale: 'APPS_MESSAGES',
icon: <MessageIcon fontSize='default' />, icon: <MessageIcon fontSize="large" />,
notificationIcon: <MessageIcon fontSize='small' />, notificationIcon: <MessageIcon fontSize='small' />,
backgroundColor: MESSAGES_APP_PRIMARY_COLOR, backgroundColor: MESSAGES_APP_PRIMARY_COLOR,
color: MESSAGES_APP_TEXT_COLOR, color: MESSAGES_APP_TEXT_COLOR,
@@ -81,7 +82,7 @@ export const APPS: IAppConfig[] = [
{ {
id: 'CONTACTS', id: 'CONTACTS',
nameLocale: 'APPS_CONTACTS', nameLocale: 'APPS_CONTACTS',
icon: <ContactsIcon />, icon: <ContactsIcon fontSize="large" />,
notificationIcon: <ContactsIcon fontSize='small' />, notificationIcon: <ContactsIcon fontSize='small' />,
backgroundColor: CONTACTS_APP_PRIMARY_COLOR, backgroundColor: CONTACTS_APP_PRIMARY_COLOR,
color: CONTACTS_APP_TEXT_COLOR, color: CONTACTS_APP_TEXT_COLOR,
@@ -93,7 +94,7 @@ export const APPS: IAppConfig[] = [
{ {
id: 'CALCULATOR', id: 'CALCULATOR',
nameLocale: 'APPS_CALCULATOR', nameLocale: 'APPS_CALCULATOR',
icon: <CalculatorIcon />, icon: <CalculatorIcon fontSize="large" />,
notificationIcon: <CalculatorIcon fontSize='small' />, notificationIcon: <CalculatorIcon fontSize='small' />,
backgroundColor: purple[500], backgroundColor: purple[500],
color: grey[50], color: grey[50],
@@ -105,7 +106,7 @@ export const APPS: IAppConfig[] = [
{ {
id: 'SETTINGS', id: 'SETTINGS',
nameLocale: 'APPS_SETTINGS', nameLocale: 'APPS_SETTINGS',
icon: <SettingsIcon />, icon: <SettingsIcon fontSize="large" />,
notificationIcon: <SettingsIcon fontSize='small' />, notificationIcon: <SettingsIcon fontSize='small' />,
backgroundColor: '#383838', backgroundColor: '#383838',
color: grey[50], color: grey[50],
@@ -117,7 +118,7 @@ export const APPS: IAppConfig[] = [
{ {
id: 'BANK', id: 'BANK',
nameLocale: 'APPS_BANK', nameLocale: 'APPS_BANK',
icon: <FontAwesomeIcon icon={faWonSign} size='xs' />, icon: <FontAwesomeIcon icon={faWonSign} />,
notificationIcon: <FontAwesomeIcon icon={faWonSign} size='xs' />, notificationIcon: <FontAwesomeIcon icon={faWonSign} size='xs' />,
backgroundColor: blue[900], backgroundColor: blue[900],
color: common.white, color: common.white,
@@ -127,7 +128,7 @@ export const APPS: IAppConfig[] = [
{ {
id: 'TWITTER', id: 'TWITTER',
nameLocale: 'APPS_TWITTER', nameLocale: 'APPS_TWITTER',
icon: <FontAwesomeIcon icon={faTwitter} fixedWidth size='xs' />, icon: <FontAwesomeIcon icon={faTwitter} fixedWidth />,
notificationIcon: <FontAwesomeIcon icon={faTwitter} fixedWidth size='xs' />, notificationIcon: <FontAwesomeIcon icon={faTwitter} fixedWidth size='xs' />,
backgroundColor: blue[600], backgroundColor: blue[600],
color: common.white, color: common.white,
@@ -141,8 +142,8 @@ export const APPS: IAppConfig[] = [
nameLocale: 'APPS_SELLOUT', nameLocale: 'APPS_SELLOUT',
icon: <FontAwesomeIcon icon={faAd} fixedWidth />, icon: <FontAwesomeIcon icon={faAd} fixedWidth />,
notificationIcon: <FontAwesomeIcon icon={faAd} fixedWidth size='xs' />, notificationIcon: <FontAwesomeIcon icon={faAd} fixedWidth size='xs' />,
backgroundColor: red[500], backgroundColor: SELLOUT_APP_PRIMARY_COLOR,
color: common.white, color: SELLOUT_APP_ICON_COLOR,
path: '/sellout', path: '/sellout',
Route: () => ( Route: () => (
<AppRoute id='SELLOUT' path='/sellout' component={SelloutApp} /> <AppRoute id='SELLOUT' path='/sellout' component={SelloutApp} />
@@ -155,8 +156,8 @@ export const APPS: IAppConfig[] = [
notificationIcon: ( notificationIcon: (
<FontAwesomeIcon icon={faStickyNote} fixedWidth size='xs' /> <FontAwesomeIcon icon={faStickyNote} fixedWidth size='xs' />
), ),
backgroundColor: yellow[800], backgroundColor: NOTES_APP_PRIMARY_COLOR,
color: common.white, color: NOTES_APP_ICON_COLOR,
path: '/notes', path: '/notes',
Route: () => <AppRoute id='NOTES' path='/notes' component={NotesApp} />, Route: () => <AppRoute id='NOTES' path='/notes' component={NotesApp} />,
}, },
@@ -0,0 +1,76 @@
import React from 'react';
import CallIcon from '@material-ui/icons/Call';
import CallEndIcon from '@material-ui/icons/CallEnd';
import { useCall } from '../hooks/useCall';
import { useCallModal } from '../hooks/useCallModal';
import { StatusIconButton } from '../../../ui/components/StatusIconButton';
import { Box, makeStyles } from '@material-ui/core';
import { useHistory } from 'react-router-dom';
const useStyles = makeStyles((theme) => ({
icon: {
color: theme.palette.secondary.contrastText,
},
}));
const SIZES_SPACING = {
small: 1,
medium: 3,
};
export const CallControls = ({ size }: { size?: 'small' | 'medium' }) => {
const classes = useStyles();
const history = useHistory();
const { setModal } = useCallModal();
const { call, endCall, acceptCall, rejectCall } = useCall();
if (!call) {
return null;
}
const handleAcceptCall = (e) => {
e.stopPropagation();
history.push('/call');
acceptCall();
};
const handleRejectCall = (e) => {
e.stopPropagation();
setModal(false);
rejectCall();
};
const handleEndCall = (e) => {
e.stopPropagation();
setModal(false);
endCall();
};
const { accepted, isTransmitter } = call;
if (accepted || isTransmitter) {
return (
<StatusIconButton color='error' size={size} onClick={handleEndCall}>
<CallEndIcon />
</StatusIconButton>
);
}
return (
<>
<Box m={SIZES_SPACING[size] || 1} display='inline'>
<StatusIconButton color='error' size={size} onClick={handleRejectCall}>
<CallEndIcon className={classes.icon} />
</StatusIconButton>
</Box>
<Box m={SIZES_SPACING[size] || 1} display='inline'>
<StatusIconButton
color='success'
size={size}
onClick={handleAcceptCall}
>
<CallIcon className={classes.icon} />
</StatusIconButton>
</Box>
</>
);
};
@@ -0,0 +1,27 @@
import React from 'react';
import { AppWrapper } from '../../../ui/components/AppWrapper';
import { AppContent } from '../../../ui/components/AppContent';
import { useCall } from '../hooks/useCall';
import useStyles from './modal.styles';
import CallTimer from './CallTimer';
import { CallControls } from './CallControls';
import { Box } from '@material-ui/core';
export const CallModal = () => {
const classes = useStyles();
const { call } = useCall();
return (
<AppWrapper>
<AppContent>
<Box pt={24}>
<h1 style={{ textAlign: 'center' }}>{call?.transmitter}</h1>
<CallTimer isAccepted={call?.accepted} />
</Box>
<div className={classes.actions}>
<CallControls size="medium" />
</div>
</AppContent>
</AppWrapper>
);
};
@@ -0,0 +1,35 @@
import React from 'react';
import { Box, makeStyles } from '@material-ui/core';
import { CallControls } from './CallControls';
interface ICallNotificationProps {
onAccept(): void;
onReject(): void;
}
const useStyles = makeStyles((theme) => ({
root: {
paddingBottom: '48px',
},
controls: {
position: 'absolute',
bottom: theme.spacing(1),
right: '4px',
},
}));
export const CallNotification = ({
children,
}: {
children: React.ReactNode;
}) => {
const classes = useStyles();
return (
<div className={classes.root}>
<Box>{children}</Box>
<Box className={classes.controls}>
<CallControls size='small' />
</Box>
</div>
);
};
@@ -11,7 +11,7 @@ const useStyles = makeStyles((theme: Theme) => ({
bottom: '10%', bottom: '10%',
}, },
actionButton: { actionButton: {
margin: 20, margin: 10,
}, },
})); }));
File renamed without changes.
+36
View File
@@ -0,0 +1,36 @@
import { useRecoilState } from 'recoil';
import { CallProps } from '../../../common/typings/call';
import Nui from '../../nui-events/utils/Nui';
import { callerState } from './state';
interface CallHook {
call: CallProps;
setCall: (details: any) => void;
acceptCall(): void;
rejectCall(): void;
endCall(): void;
}
export const useCall = (): CallHook => {
const [call, setCall] = useRecoilState(callerState.currentCall);
const acceptCall = () => {
Nui.send('phone:acceptCall', {
transmitterNumber: call.transmitter,
});
};
const rejectCall = () => {
Nui.send('phone:rejectCall', {
phoneNumber: call.transmitter,
});
};
const endCall = () => {
Nui.send('phone:endCall', {
transmitterNumber: call.transmitter,
});
};
return { call, setCall, acceptCall, rejectCall, endCall };
};
@@ -6,7 +6,7 @@ interface ModalProps {
setModal: (show: boolean) => void; setModal: (show: boolean) => void;
} }
export const useModal = (): ModalProps => { export const useCallModal = (): ModalProps => {
const [modal, setModal] = useRecoilState(callerState.callModal); const [modal, setModal] = useRecoilState(callerState.callModal);
return { modal, setModal } return { modal, setModal }
} }
+121
View File
@@ -0,0 +1,121 @@
import React, { useEffect, useState } from 'react';
import { useNuiEvent } from '../../nui-events/hooks/useNuiEvent';
import { useSetRecoilState } from 'recoil';
import { callerState } from './state';
import { useNotifications } from '../../notifications/hooks/useNotifications';
import { useTranslation } from 'react-i18next';
import { CallNotification } from '../components/CallNotification';
import { useCall } from './useCall';
import { CallProps } from '../../../common/typings/call';
import { useApp } from '../../apps/hooks/useApps';
import InjectDebugData from '../../debug/InjectDebugData';
import { useCallModal } from './useCallModal';
import { useHistory, useLocation } from 'react-router-dom';
const NOTIFICATION_ID = 'call:current';
/* InjectDebugData<CallProps | boolean>([
{
app: 'CALL',
method: 'setCaller',
data: {
accepted: false,
isTransmitter: false,
transmitter: 'Chip',
receiver: 'Taso',
active: true,
},
},
{
app: 'CALL',
method: 'callModal',
data: true,
},
]); */
export const useCallService = () => {
const { t } = useTranslation();
const { modal } = useCallModal();
const history = useHistory();
const { pathname } = useLocation();
const {
addNotificationAlert,
removeId,
addNotification,
} = useNotifications();
const { call, setCall } = useCall();
const { icon, notificationIcon } = useApp('DIALER');
const setModal = useSetRecoilState(callerState.callModal);
const [modalHasBeenOpenedThisCall, setModalOpened] = useState<boolean>(false);
const callNotificationBase = {
app: 'CALL',
id: NOTIFICATION_ID,
cantClose: true,
icon,
onClick: () => history.push('/call'),
notificationIcon,
};
useEffect(() => {
setModalOpened(!!modal);
}, [modal]);
useEffect(() => {
if (!modal && pathname === '/call') {
history.replace('/');
}
if (modal && !modalHasBeenOpenedThisCall && pathname !== '/call') {
history.push('/call');
}
}, [history, modal, pathname, modalHasBeenOpenedThisCall]);
const _setCall = (_call: CallProps) => {
setCall(_call);
if (!_call || !_call.active) {
removeId(NOTIFICATION_ID);
return;
}
if (_call.accepted) {
removeId(NOTIFICATION_ID);
addNotification({
...callNotificationBase,
content: (
<CallNotification>
{t('APPS_DIALER_CURRENT_CALL_WITH', {
transmitter: _call.transmitter,
})}
</CallNotification>
),
title: t('APPS_DIALER_CURRENT_CALL_TITLE'),
});
}
if (!_call.isTransmitter && !_call.accepted) {
removeId(NOTIFICATION_ID);
addNotificationAlert(
{
...callNotificationBase,
title: t('APPS_DIALER_INCOMING_CALL_TITLE', {
transmitter: _call.transmitter,
}),
keepWhenPhoneClosed: true,
content: (
<CallNotification>
{t('APPS_DIALER_TRANSMITTER_IS_CALLING', {
transmitter: _call.transmitter,
})}
</CallNotification>
),
},
true
);
}
};
useNuiEvent<CallProps>('CALL', 'setCaller', _setCall, call);
useNuiEvent<boolean>('CALL', 'callModal', setModal);
};
File renamed without changes.
+3 -3
View File
@@ -1,7 +1,7 @@
interface DebugEvent { interface DebugEvent<P = any> {
app: string; app: string;
method: string; method: string;
data: any; data: P;
} }
// TODO: This should be unit tested // TODO: This should be unit tested
@@ -27,7 +27,7 @@ interface DebugEvent {
* } * }
* ]) * ])
**/ **/
const InjectDebugData = (events: DebugEvent[], timer = 1000) => { const InjectDebugData = <P>(events: DebugEvent<P>[], timer = 1000) => {
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
for (const event of events) { for (const event of events) {
setTimeout(() => { setTimeout(() => {
@@ -1,7 +1,7 @@
import { useCallback, useEffect } from 'react'; import { useCallback, useEffect, useRef } from 'react';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { atom, useSetRecoilState, useRecoilValue } from 'recoil'; import { atom, useSetRecoilState, useRecoilValue } from 'recoil';
import Nui from '../../nui-events/utils/Nui'; import { usePhone } from '../../phone/hooks/usePhone';
const keyboardState = { const keyboardState = {
ArrowRight: atom({ ArrowRight: atom({
@@ -46,8 +46,9 @@ const validKeys = [
const isKeyValid = (key) => validKeys.indexOf(key) !== -1; const isKeyValid = (key) => validKeys.indexOf(key) !== -1;
export const useInitKeyboard = () => { export const useKeyboardService = () => {
const history = useHistory(); const history = useHistory();
const { closePhone } = usePhone();
const getters = { const getters = {
ArrowRight: useRecoilValue(keyboardState.ArrowRight), ArrowRight: useRecoilValue(keyboardState.ArrowRight),
ArrowLeft: useRecoilValue(keyboardState.ArrowLeft), ArrowLeft: useRecoilValue(keyboardState.ArrowLeft),
@@ -58,21 +59,26 @@ export const useInitKeyboard = () => {
Escape: useRecoilValue(keyboardState.Escape), Escape: useRecoilValue(keyboardState.Escape),
}; };
const handlers = useRef(new Map());
const setEscape = useSetRecoilState<any>(keyboardState.Escape); const setEscape = useSetRecoilState<any>(keyboardState.Escape);
const setBackspace = useSetRecoilState(keyboardState.Backspace); const setBackspace = useSetRecoilState(keyboardState.Backspace);
useEffect(
function registerCustomKeys() {
Object.keys(getters).forEach((g) => {
handlers.current.set(g, getters[g]);
});
},
[getters]
);
useEffect( useEffect(
function handleNUIKeyboardMessage() { function handleNUIKeyboardMessage() {
function onKeyUp(event) { function onKeyUp(event) {
const { key } = event; const { key } = event;
const callback = getters[key]; const callback = handlers.current.get(key);
if ( if (isKeyValid(key) && callback && callback.call) {
isKeyValid(key) && return callback(event);
callback &&
callback.handler &&
callback.handler.call
) {
return callback.handler(event);
} }
} }
@@ -82,35 +88,22 @@ export const useInitKeyboard = () => {
[getters] [getters]
); );
const escapeHandler = useCallback(() => Nui.send('phone:close'), []); const backspaceHandler = useCallback(
(event) => {
const backspaceHandler = useCallback((event) => { if (['input', 'textarea'].includes(event.target.nodeName.toLowerCase())) {
if (['input', 'textarea'].includes(event.target.nodeName.toLowerCase())) { // Dont anything if we are typing something :)
// Dont anything if we are typing something :) return;
return; }
} history.goBack();
history.goBack(); },
}, [history]); [history]
);
useEffect( useEffect(
function registerDefaultHandlers() { function registerDefaultHandlers() {
setEscape({ handler: escapeHandler }); handlers.current.set('Escape', () => closePhone());
setBackspace({ handler: backspaceHandler }); handlers.current.set('Backspace', backspaceHandler);
}, },
[setEscape, setBackspace, history, escapeHandler, backspaceHandler] [setEscape, setBackspace, history, backspaceHandler, closePhone]
); );
}; };
export const useKeyboard = () => {
const setters = {
ArrowRight: useSetRecoilState(keyboardState.ArrowRight),
ArrowLeft: useSetRecoilState(keyboardState.ArrowLeft),
ArrowUp: useSetRecoilState(keyboardState.ArrowUp),
ArrowDown: useSetRecoilState(keyboardState.ArrowDown),
Enter: useSetRecoilState(keyboardState.Enter),
};
return (key, handler) => {
setters[key]({ handler });
};
};
@@ -7,9 +7,9 @@ import {
import KeyboardArrowLeftIcon from '@material-ui/icons/KeyboardArrowLeft'; import KeyboardArrowLeftIcon from '@material-ui/icons/KeyboardArrowLeft';
import AppsIcon from '@material-ui/icons/Apps'; import AppsIcon from '@material-ui/icons/Apps';
import RadioButtonUncheckedIcon from '@material-ui/icons/RadioButtonUnchecked'; import RadioButtonUncheckedIcon from '@material-ui/icons/RadioButtonUnchecked';
import { useHistory } from 'react-router-dom'; import { useHistory, useRouteMatch } from 'react-router-dom';
import { usePhone } from '../../phone/hooks/usePhone';
import Nui from '../../nui-events/utils/Nui'; import { useNotifications } from '../../notifications/hooks/useNotifications';
const useStyles = makeStyles((theme) => ({ const useStyles = makeStyles((theme) => ({
root: { root: {
@@ -19,17 +19,18 @@ const useStyles = makeStyles((theme) => ({
})); }));
export const Navigation = () => { export const Navigation = () => {
const closePhone = () => {
console.log('Phone closed');
Nui.send('phone:close');
};
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const { isExact } = useRouteMatch('/');
const { closePhone } = usePhone();
const { setBarUncollapsed } = useNotifications();
return ( return (
<BottomNavigation <BottomNavigation
className={classes.root} className={classes.root}
onChange={(_e, value) => value()} onChange={(_e, value) => {
setBarUncollapsed(false);
value();
}}
> >
<BottomNavigationAction <BottomNavigationAction
label='Home' label='Home'
@@ -38,12 +39,12 @@ export const Navigation = () => {
/> />
<BottomNavigationAction <BottomNavigationAction
label='Close' label='Close'
value={() => closePhone()} value={closePhone}
icon={<RadioButtonUncheckedIcon />} icon={<RadioButtonUncheckedIcon />}
/> />
<BottomNavigationAction <BottomNavigationAction
label='Back' label='Back'
value={() => history.goBack()} value={() => !isExact && history.goBack()}
icon={<KeyboardArrowLeftIcon />} icon={<KeyboardArrowLeftIcon />}
/> />
</BottomNavigation> </BottomNavigation>
@@ -0,0 +1,82 @@
import React from 'react';
import CloseIcon from '@material-ui/icons/Close';
import { Box, IconButton, makeStyles, Slide } from '@material-ui/core';
import { useNotifications } from '../hooks/useNotifications';
import { Alert, AlertTitle } from '@material-ui/lab';
const useStyles = makeStyles((theme) => ({
snackbar: {
marginTop: '-710px',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
alert: {
'& .MuiAlert-action': {
top: theme.spacing(1),
right: theme.spacing(2),
position: 'absolute',
},
position: 'relative',
cursor: 'pointer',
width: '370px',
height: '120px',
zIndex: 50,
backgroundColor: theme.palette.background.paper,
color: theme.palette.text.primary,
'& .MuiAlert-icon': {
color: theme.palette.text.primary,
},
},
alertContent: {
display: '-webkit-box',
maxWidth: '360px',
height: '60px',
margin: '0 auto',
'-webkit-line-clamp': 3,
'-webkit-box-orient': 'vertical',
overflow: 'hidden',
textOverflow: 'ellipsis',
},
}));
export const NotificationAlert = () => {
const classes = useStyles();
const { currentAlert } = useNotifications();
return (
<div className={classes.snackbar}>
<Slide in={!!currentAlert} mountOnEnter unmountOnExit>
<Alert
action={
<IconButton
color='primary'
size='small'
onClick={(e) => {
e.stopPropagation();
currentAlert?.onCloseAlert(e);
}}
>
<CloseIcon fontSize='small' />
</IconButton>
}
onClick={(e) => currentAlert?.onClickAlert(e)}
icon={currentAlert?.icon || false}
className={classes.alert}
elevation={6}
>
<AlertTitle>
<Box width='282px' whiteSpace='nowrap'>
<Box overflow='hidden' component='div' textOverflow='ellipsis'>
{currentAlert?.title}
</Box>
</Box>
</AlertTitle>
<Box component='div' className={classes.alertContent}>
{currentAlert?.content}
</Box>
</Alert>
</Slide>
</div>
);
};
@@ -1,4 +1,4 @@
import React, { useState } from 'react'; import React from 'react';
import { import {
makeStyles, makeStyles,
Typography, Typography,
@@ -8,18 +8,14 @@ import {
Paper, Paper,
Box, Box,
List, List,
ListItem,
ListItemText,
Divider, Divider,
ListItemAvatar,
} from '@material-ui/core'; } from '@material-ui/core';
import SignalIcon from '@material-ui/icons/SignalCellular3Bar'; import SignalIcon from '@material-ui/icons/SignalCellular3Bar';
import CloseIcon from '@material-ui/icons/Close';
import Battery90Icon from '@material-ui/icons/Battery90'; import Battery90Icon from '@material-ui/icons/Battery90';
import ArrowDropUpIcon from '@material-ui/icons/ArrowDropUp'; import ArrowDropUpIcon from '@material-ui/icons/ArrowDropUp';
import Default from '../../../config/default.json'; import Default from '../../../config/default.json';
import { useNotifications } from '../hooks/useNotifications'; import { useNotifications } from '../hooks/useNotifications';
import { useHistory } from 'react-router-dom'; import { NotificationItem } from './NotificationItem';
const useStyles = makeStyles((theme) => ({ const useStyles = makeStyles((theme) => ({
root: { root: {
@@ -67,13 +63,16 @@ const useStyles = makeStyles((theme) => ({
}, },
})); }));
export const NotificationBar = ({ forceUncollapse }: { forceUncollapse: boolean }) => { export const NotificationBar = () => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory();
const { icons, notifications, removeNotification } = useNotifications(); const {
icons,
const [uncollapsed, setUncollapsed] = useState<boolean>(false); notifications,
removeNotification,
barUncollapsed,
setBarUncollapsed,
} = useNotifications();
return ( return (
<> <>
@@ -83,7 +82,7 @@ export const NotificationBar = ({ forceUncollapse }: { forceUncollapse: boolean
justify='space-between' justify='space-between'
wrap='nowrap' wrap='nowrap'
onClick={() => { onClick={() => {
setUncollapsed(!uncollapsed); setBarUncollapsed((curr) => !curr);
}} }}
> >
<Grid container item wrap='nowrap'> <Grid container item wrap='nowrap'>
@@ -120,41 +119,30 @@ export const NotificationBar = ({ forceUncollapse }: { forceUncollapse: boolean
</Grid> </Grid>
</Grid> </Grid>
</Grid> </Grid>
<Slide direction='down' in={forceUncollapse || uncollapsed}> <Slide direction='down' in={barUncollapsed}>
<Paper square className={classes.drawer}> <Paper square className={classes.drawer}>
<Box p={2}> <Box py={2}>
<List> <List>
<Divider /> <Divider />
{notifications.map(({ href, title, content, icon }, idx) => ( {notifications.map((notification, idx) => (
<ListItem <NotificationItem
divider key={idx}
button {...notification}
onClick={() => { onClose={(e) => {
if (href) { e.stopPropagation();
history.push(href); notification.onClose?.(notification);
setUncollapsed(false); if (notifications.length === 1) {
setBarUncollapsed(false);
}
removeNotification(idx);
}}
onClickClose={() => {
setBarUncollapsed(false);
if (!notification.cantClose) {
removeNotification(idx); removeNotification(idx);
} }
}} }}
className={classes.notificationItem} />
key={idx}
>
{icon && <ListItemAvatar>{icon}</ListItemAvatar>}
<ListItemText secondary={content}>{title}</ListItemText>
<IconButton
className={classes.closeNotifBtn}
size='small'
onClick={(e) => {
e.stopPropagation();
if (notifications.length === 1) {
setUncollapsed(false);
}
removeNotification(idx);
}}
>
<CloseIcon color='primary' />
</IconButton>
</ListItem>
))} ))}
</List> </List>
</Box> </Box>
@@ -162,7 +150,7 @@ export const NotificationBar = ({ forceUncollapse }: { forceUncollapse: boolean
<IconButton <IconButton
className={classes.collapseBtn} className={classes.collapseBtn}
size='small' size='small'
onClick={() => setUncollapsed(false)} onClick={() => setBarUncollapsed(false)}
> >
<ArrowDropUpIcon /> <ArrowDropUpIcon />
</IconButton> </IconButton>
@@ -0,0 +1,60 @@
import React from 'react';
import CloseIcon from '@material-ui/icons/Close';
import {
IconButton,
ListItem,
ListItemAvatar,
ListItemText,
makeStyles,
Theme,
} from '@material-ui/core';
import { INotification } from '../providers/NotificationsProvider';
const useStyles = makeStyles<Theme, { cantClose: boolean }>((theme) => ({
closeNotifBtn: {
position: 'absolute',
right: '8px',
top: '8px',
},
notificationItem: {
paddingRight: ({ cantClose }) => (cantClose ? '8px' : '28px'),
position: 'relative',
},
}));
export const NotificationItem = ({
onClose,
onClickClose,
...notification
}: INotification & {
onClose: (e: any) => void;
onClickClose: (e: any) => void;
}) => {
const { title, icon, content, cantClose, onClick } = notification;
const classes = useStyles({ cantClose });
return (
<ListItem
divider
button
onClick={(e) => {
if (onClick) {
onClick(notification);
onClickClose(e);
}
}}
className={classes.notificationItem}
>
{icon && <ListItemAvatar>{icon}</ListItemAvatar>}
<ListItemText secondary={content}>{title}</ListItemText>
{!cantClose && (
<IconButton
className={classes.closeNotifBtn}
size='small'
onClick={onClose}
>
<CloseIcon color='primary' />
</IconButton>
)}
</ListItem>
);
};
@@ -0,0 +1 @@
export const DEFAULT_ALERT_HIDE_TIME = 3000;
@@ -1,14 +1,34 @@
import React, { createContext, useState, useCallback, useMemo } from 'react'; import React, {
createContext,
useState,
useCallback,
useMemo,
useRef,
useEffect,
} from 'react';
import { useRecoilValue } from 'recoil';
import { phoneState } from '../../phone/hooks/state';
import { DEFAULT_ALERT_HIDE_TIME } from '../notifications.constants';
export interface INotification { export interface INotification {
app: string; app: string;
id?: string;
title: string; title: string;
content?: React.ReactNode; content?: React.ReactNode;
icon?: JSX.Element; icon?: JSX.Element;
notificationIcon?: JSX.Element; notificationIcon?: JSX.Element;
href?: string; cantClose?: boolean;
keepWhenPhoneClosed?: boolean;
onClose?: (notification: INotification) => void;
onClick?: (notification: INotification) => void;
} }
type INotificationAlert = INotification & {
onClickAlert(e?: any): void;
onCloseAlert(e?: any): void;
resolve(): void;
};
interface INotificationIcon { interface INotificationIcon {
key: string; key: string;
icon: JSX.Element; icon: JSX.Element;
@@ -16,40 +36,164 @@ interface INotificationIcon {
} }
export const NotificationsContext = createContext<{ export const NotificationsContext = createContext<{
barUncollapsed: boolean;
setBarUncollapsed: (v: boolean | ((c: boolean) => boolean)) => void;
notifications: INotification[]; notifications: INotification[];
currentAlert: INotificationAlert;
icons: INotificationIcon[]; icons: INotificationIcon[];
count: number; count: number;
removeAlerts(): void;
addOrUpdateNotification(add: INotification, update?: INotification): void;
addNotification(value: INotification): void; addNotification(value: INotification): void;
updateNotification(idx: number, value: INotification): void;
removeNotification(idx: number): void; removeNotification(idx: number): void;
updateId(id: string, value: Partial<INotification>): void;
removeId(id: string): void;
hasNotification(app: string): number;
addNotificationAlert(
n: INotification,
persist: boolean,
update?: Partial<INotification>
);
}>(null); }>(null);
export function NotificationsProvider({ children }) { export function NotificationsProvider({ children }) {
const isPhoneOpen = useRecoilValue(phoneState.visibility);
const [barUncollapsed, setBarUncollapsed] = useState<boolean>(false);
const [notifications, setNotifications] = useState<INotification[]>([]); const [notifications, setNotifications] = useState<INotification[]>([]);
const alertTimeout = useRef<NodeJS.Timeout>();
const [alerts, setAlerts] = useState<
Array<[INotification, boolean, Partial<INotification>]>
>([]);
const [currentAlert, setCurrentAlert] = useState<INotificationAlert>();
useEffect(() => {
if (isPhoneOpen && currentAlert && currentAlert.keepWhenPhoneClosed) {
currentAlert.resolve();
}
}, [isPhoneOpen, currentAlert]);
const updateNotification = useCallback( const updateNotification = useCallback(
(idx: number, value: INotification) => { (idx: number, value: INotification) => {
setNotifications((all) => { setNotifications((all) => {
const updated = [...all]; const updated = [...all];
updated.splice(idx, 0, value); updated.splice(idx, 1, value);
return updated; return updated;
}); });
}, },
[] []
); );
const removeNotification = useCallback((idx) => { const removeNotification = (idx) => {
setNotifications((all) => { setNotifications((all) => {
const updated = [...all]; const updated = all;
updated.splice(idx, 1); updated.splice(idx, 1);
return updated; return [...updated];
}); });
}, []); };
const addNotification = useCallback((value: INotification) => { const addNotification = useCallback((value: INotification) => {
setNotifications((all) => [value, ...all]); setNotifications((all) => [value, ...all]);
}, []); }, []);
/**
* Checks if a notification exists for current app
* and returns its index or -1 if not found.
*/
const hasNotification = useCallback(
(appId: string): number => {
return notifications.findIndex((n) => n.app === appId);
},
[notifications]
);
const addOrUpdateNotification = useCallback(
(add: INotification, update?: INotification) => {
const exists = hasNotification(add.app);
if (update && exists !== -1) {
updateNotification(exists, update);
return;
}
addNotification(add);
},
[addNotification, hasNotification, updateNotification]
);
const _showAlert = useCallback(
(n: INotification, persist: boolean, update: Partial<INotification>) => {
return new Promise<void>((res) => {
const resolve = () => {
if (persist) {
addOrUpdateNotification(n, update ? { ...n, ...update } : null);
}
res();
};
const onExit = (cb) => () => {
cb?.(n);
clearTimeout(alertTimeout.current);
resolve();
};
setCurrentAlert({
...n,
resolve,
onClickAlert: onExit(n.onClick),
onCloseAlert: onExit(n.onClose),
});
if (n.keepWhenPhoneClosed) {
return;
}
alertTimeout.current = setTimeout(() => {
resolve();
// If you change or remove the 300 i'll kill your pet - Kidz /s
// Really, this makes it work nicely with usePhoneVisibility :)
}, DEFAULT_ALERT_HIDE_TIME + 300);
});
},
[addOrUpdateNotification]
);
const addNotificationAlert = (
n: INotification,
persist?: boolean,
update?: Partial<INotification>
) => {
setAlerts((curr) => [...curr, [n, persist, update]]);
};
const removeId = (id: string) => {
const idx = notifications.findIndex((n) => n.id === id);
if (idx !== -1) {
removeNotification(idx);
}
};
const updateId = (id: string, value: Partial<INotification>) => {
const idx = notifications.findIndex((n) => n.id === id);
if (idx !== -1) {
const curr = { ...notifications[idx], ...value };
updateNotification(idx, curr);
}
};
useEffect(() => {
if (!currentAlert && alerts.length) {
_showAlert(...alerts[0]).then(() => {
setAlerts((curr) => {
const newQueue = curr;
curr.shift();
return newQueue;
});
setCurrentAlert(null);
});
}
}, [_showAlert, alerts, currentAlert]);
const icons: INotificationIcon[] = useMemo( const icons: INotificationIcon[] = useMemo(
() => () =>
notifications.reduce((icons, curr) => { notifications.reduce((icons, curr) => {
@@ -64,13 +208,26 @@ export function NotificationsProvider({ children }) {
[notifications] [notifications]
); );
const removeAlerts = () => {
setAlerts([]);
setCurrentAlert(null);
};
return ( return (
<NotificationsContext.Provider <NotificationsContext.Provider
value={{ value={{
setBarUncollapsed,
barUncollapsed,
currentAlert,
notifications, notifications,
removeAlerts,
addNotification, addNotification,
updateNotification,
removeNotification, removeNotification,
updateId,
removeId,
hasNotification,
addNotificationAlert,
addOrUpdateNotification,
icons, icons,
count: notifications.length, count: notifications.length,
}} }}
+10 -13
View File
@@ -16,17 +16,16 @@ interface IOptions {
* @param options Any options to pass to the addEventListener * @param options Any options to pass to the addEventListener
**/ **/
export const useNuiEvent = ( const defaultOptions = {};
export const useNuiEvent = <S = Record<string, unknown>>(
app: string, app: string,
method: string, method: string,
handler: Function, handler: Function,
options: IOptions = {}, currentState?: S,
currentState?: Record<string, unknown> options: IOptions = defaultOptions
) => { ) => {
const savedHandler: MutableRefObject<any> = useRef(); const savedHandler: MutableRefObject<any> = useRef();
// Destructure passed options
const { capture, passive, once } = options;
// When handler value changes set mutable ref to handler val // When handler value changes set mutable ref to handler val
useEffect(() => { useEffect(() => {
@@ -44,15 +43,13 @@ export const useNuiEvent = (
data: event.data, data: event.data,
level: 1, level: 1,
}); });
const newData = currentState ? { ...currentState, ...data } : data const newData = currentState ? { ...currentState, ...data } : data;
savedHandler.current(newData) savedHandler.current(newData);
} }
}; };
// Why are destructing then restructuring option data?
const opts = { capture, passive, once };
window.addEventListener(eventName, eventListener, opts); window.addEventListener(eventName, eventListener, options);
// Remove Event Listener on component cleanup // Remove Event Listener on component cleanup
return () => window.removeEventListener(eventName, eventListener, opts); return () => window.removeEventListener(eventName, eventListener, options);
}, [app, method, capture, passive, once, currentState]); }, [app, method, currentState, options]);
}; };
+20 -6
View File
@@ -1,15 +1,29 @@
import { useRecoilState } from 'recoil'; import { useRecoilValue } from 'recoil';
import { phoneState } from './state';
import { IServerConfig } from '../../../common/typings/config'; import { IServerConfig } from '../../../common/typings/config';
import ServerConfig from '../../../config.autogen.json'; import ServerConfig from '../../../config.autogen.json';
import { useNotifications } from '../../notifications/hooks/useNotifications';
import Nui from '../../nui-events/utils/Nui';
import { phoneState } from './state';
interface IUsePhone { interface IUsePhone {
visibility: boolean;
setVisibility(v: boolean): void;
config?: IServerConfig; config?: IServerConfig;
openPhone(): void;
closePhone(): void;
isPhoneOpen: boolean;
} }
export const usePhone = (): IUsePhone => { export const usePhone = (): IUsePhone => {
const [visibility, setVisibility] = useRecoilState(phoneState.visibility); const isPhoneOpen = useRecoilValue(phoneState.visibility);
return { visibility, setVisibility, config: ServerConfig as any };
const { removeAlerts } = useNotifications();
const closePhone = () => {
removeAlerts();
Nui.send('phone:close');
};
const openPhone = () => {
Nui.send('phone:open');
};
return { config: ServerConfig as any, closePhone, openPhone, isPhoneOpen };
}; };
+28 -34
View File
@@ -1,56 +1,50 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useEffect, useMemo, useRef, useState } from 'react';
import { useRecoilState } from 'recoil';
import { useSettings } from '../../../apps/settings/hooks/useSettings'; import { useSettings } from '../../../apps/settings/hooks/useSettings';
import { useNotifications } from '../../notifications/hooks/useNotifications'; import { useNotifications } from '../../notifications/hooks/useNotifications';
import { usePhone } from './usePhone'; import { DEFAULT_ALERT_HIDE_TIME } from '../../notifications/notifications.constants';
import { phoneState } from './state';
export const usePhoneVisibility = () => { export const usePhoneVisibility = () => {
const { setVisibility, visibility } = usePhone(); const [visibility, setVisibility] = useRecoilState(phoneState.visibility);
const { count } = useNotifications(); const { currentAlert } = useNotifications();
const [{ zoom }] = useSettings(); const [{ zoom }] = useSettings();
const [notifVisibility, setNotifVisibility] = useState<boolean>(false); const [notifVisibility, setNotifVisibility] = useState<boolean>(false);
const isNotificationVisibleOnly = useMemo(
() => !!(!visibility && count > 0),
[visibility, count]
);
const notificationTimer = useRef<NodeJS.Timeout>(); const notificationTimer = useRef<NodeJS.Timeout>();
useEffect(() => { useEffect(() => {
if (isNotificationVisibleOnly) { if (visibility) {
setNotifVisibility(true); setNotifVisibility(false);
clearTimeout(notificationTimer.current);
notificationTimer.current = setTimeout(() => {
setVisibility(false);
setNotifVisibility(false);
}, 5000);
} }
return () => clearTimeout(notificationTimer.current); }, [visibility]);
}, [isNotificationVisibleOnly, setVisibility]);
useEffect(() => {
if (!visibility && currentAlert) {
setNotifVisibility(true);
if (notificationTimer.current) {
clearTimeout(notificationTimer.current);
notificationTimer.current = undefined;
}
if (currentAlert?.keepWhenPhoneClosed) {
return;
}
notificationTimer.current = setTimeout(() => {
setNotifVisibility(false);
}, DEFAULT_ALERT_HIDE_TIME);
}
}, [currentAlert, visibility, setVisibility]);
const bottom = useMemo(() => { const bottom = useMemo(() => {
if (isNotificationVisibleOnly) { if (!visibility) {
return `calc(-60% * ${zoom})`; return `calc(-70% * ${zoom})`;
} }
return 0; return 0;
}, [isNotificationVisibleOnly, zoom]); }, [visibility, zoom]);
const clickEventOverride = useCallback(
(e) => {
if (isNotificationVisibleOnly) {
e.preventDefault();
e.stopPropagation();
setVisibility(true);
}
},
[setVisibility, isNotificationVisibleOnly]
);
return { return {
bottom, bottom,
visibility: notifVisibility || visibility, visibility: notifVisibility || visibility,
uncollapseNotifications: isNotificationVisibleOnly,
clickEventOverride,
}; };
}; };
+39 -34
View File
@@ -13,70 +13,75 @@ interface ISoundOptions {
* *
* @param { volume, interrupt, loop} Additional options * @param { volume, interrupt, loop} Additional options
**/ **/
const useSound = ( const useSound = (
url: string, url: string,
{ volume = 1, interrupt = false, loop = false }: ISoundOptions = {} { volume = 1, interrupt = false, loop = false }: ISoundOptions = {}
) => { ) => {
const isMounted = useRef<boolean>(false); const [isMounted, setMounted] = useState<boolean>(false);
const soundRef = useRef<Howl>(null);
const [playing, setPlaying] = useState<boolean>(false); const [playing, setPlaying] = useState<boolean>(false);
const [sound, setSound] = useState<Howl | null>(null);
// Mount & Dismount handling // Mount & Dismount handling
useEffect(() => { useEffect(() => {
isMounted.current = true; soundRef.current?.unload();
const sound = new Howl({ setPlaying(false);
setMounted(false);
soundRef.current = new Howl({
src: url, src: url,
volume, volume: 1,
loop, loop: false,
}); });
setSound(sound);
setMounted(true);
return () => { return () => {
isMounted.current = false; soundRef.current?.unload();
soundRef.current = undefined;
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps }, [url]);
}, []);
useEffect(() => { useEffect(() => {
if (sound) { if (isMounted) {
sound.volume(volume); soundRef.current.volume(volume);
} }
// Shouldnt need to rerun if sound changes }, [volume, isMounted]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [volume]); useEffect(() => {
if (isMounted) {
soundRef.current.loop(loop);
}
}, [loop, isMounted]);
const play = useCallback(() => { const play = useCallback(() => {
if (!sound) return; if (!soundRef.current) return;
if (interrupt) return sound.stop(); if (isMounted) {
soundRef.current.play();
sound.play(); soundRef.current.once('end', () => {
if (!soundRef.current.playing()) {
if (isMounted.current) {
sound.once('end', () => {
if (!sound.playing()) {
setPlaying(false); setPlaying(false);
} }
}); });
}
if (isMounted.current) {
setPlaying(true); setPlaying(true);
} }
}, [interrupt, sound]); }, [isMounted]);
const stop = useCallback(() => { const stop = useCallback(() => {
if (!sound) return; if (!soundRef.current) return;
sound.stop(); if (isMounted) {
soundRef.current.stop();
if (isMounted.current) {
setPlaying(false); setPlaying(false);
} }
}, [sound]); }, [isMounted]);
useEffect(() => {
if (interrupt && isMounted) {
stop();
}
}, [interrupt, isMounted, stop]);
return { play, playing, stop }; return { play, playing, stop };
}; };
+24 -2
View File
@@ -1,8 +1,30 @@
import React from 'react'; import React from 'react';
import MuiAlert from '@material-ui/lab/Alert'; import MuiAlert from '@material-ui/lab/Alert';
import { makeStyles, Typography } from '@material-ui/core';
export function Alert(props) { const useStyles = makeStyles({
return <MuiAlert style={{ zIndex: 10000 }} elevation={6} variant='filled' {...props} />; root: {
zIndex: 10000,
},
msg: {
maxWidth: '300px',
wordWrap: 'break-word',
fontSize: '1em'
},
});
export function Alert({ children, ...props }) {
const classes = useStyles();
return (
<MuiAlert
className={classes.root}
elevation={6}
variant='filled'
{...props}
>
<Typography className={classes.msg}>{children}</Typography>
</MuiAlert>
);
} }
export default Alert; export default Alert;
+2 -2
View File
@@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { Box, makeStyles, Backdrop, Paper } from '@material-ui/core'; import { Box, makeStyles, Backdrop, Paper, BoxProps } from '@material-ui/core';
import { AppContentTypes } from '../interface/InterfaceUI'; import { AppContentTypes } from '../interface/InterfaceUI';
const useStyles = makeStyles(() => ({ const useStyles = makeStyles(() => ({
@@ -29,7 +29,7 @@ export const AppContent = ({
backdrop, backdrop,
onClickBackdrop, onClickBackdrop,
...props ...props
}: AppContentTypes) => { }: AppContentTypes & BoxProps) => {
const classes = useStyles(); const classes = useStyles();
return ( return (
<Paper className={classes.wrapper} square> <Paper className={classes.wrapper} square>
+38 -26
View File
@@ -1,56 +1,68 @@
import React from 'react'; import React from 'react';
import { makeStyles } from '@material-ui/core/styles'; import { fade, makeStyles, Theme } from '@material-ui/core/styles';
import Avatar from '@material-ui/core/Avatar'; import Avatar from '@material-ui/core/Avatar';
import { green } from '@material-ui/core/colors'; import { green } from '@material-ui/core/colors';
import { Badge, Button } from '@material-ui/core'; import { Badge, Button, Tooltip, Zoom } from '@material-ui/core';
import { useTranslation } from 'react-i18next';
interface IStyles { const useStyles = makeStyles<Theme, { color: string; backgroundColor: string }>(
root: any; (theme) => ({
avatar: any;
}
const useStyles = makeStyles(
(theme): IStyles => ({
root: { root: {
display: 'flex',
'& > *': {
margin: theme.spacing(1),
},
padding: 0, padding: 0,
marginTop: theme.spacing(3),
}, },
avatar: { avatar: {
'&:hover': {
backgroundColor: ({ backgroundColor }) => fade(backgroundColor, 0.6),
},
backgroundColor: ({ backgroundColor }) => backgroundColor, backgroundColor: ({ backgroundColor }) => backgroundColor,
color: ({ color }) => color, color: ({ color }) => color,
width: theme.spacing(7), boxShadow: theme.shadows[2],
height: theme.spacing(7), width: theme.spacing(8),
height: theme.spacing(8),
fontSize: theme.typography.h4.fontSize, fontSize: theme.typography.h4.fontSize,
}, },
tooltip: {
fontSize: 12,
},
}) })
); );
export const AppIcon = ({ export const AppIcon = ({
id,
nameLocale,
name, name,
icon, icon,
backgroundColor, backgroundColor,
color, color,
notification, notification,
}) => { }) => {
const { t } = useTranslation();
const classes = useStyles({ const classes = useStyles({
backgroundColor: backgroundColor || green[50], backgroundColor: backgroundColor || green[50],
color: color || green[400], color: color || green[400],
}); });
return ( return (
<Button className={classes.root}> <Tooltip
<Badge arrow
color="error" key={id}
badgeContent={notification?.badge} title={t(nameLocale)}
invisible={!notification || notification.badge < 2} placement='top'
> classes={{ tooltip: classes.tooltip }}
<Avatar className={classes.avatar}> TransitionComponent={Zoom}
{icon || name[0].toUpperCase()} >
</Avatar> <Button className={classes.root}>
</Badge> <Badge
</Button> color='error'
badgeContent={notification?.badge}
invisible={!notification || notification.badge < 2}
>
<Avatar className={classes.avatar}>
{icon || name[0].toUpperCase()}
</Avatar>
</Badge>
</Button>
</Tooltip>
); );
}; };
+24 -53
View File
@@ -1,61 +1,32 @@
import React, { useEffect } from 'react'; import React from 'react';
import { AppIcon } from './AppIcon'; import { AppIcon } from './AppIcon';
import { useTranslation } from 'react-i18next'; import { Box, Grid } from '@material-ui/core';
import { Grid, makeStyles, Tooltip, Zoom } from '@material-ui/core';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { useKeyboard } from '../../os/keyboard/hooks/useKeyboard';
const useStyles = makeStyles((theme) => ({ export const GridMenu = ({
root: { items,
marginTop: theme.spacing(3), Component = AppIcon,
}, xs = undefined,
item: { }) => {
marginTop: theme.spacing(3),
width: '20%',
},
tooltip: {
fontSize: 12,
},
}));
export const GridMenu = ({ items, Component = AppIcon }) => {
const setKey = useKeyboard();
const classes = useStyles();
const { t } = useTranslation();
useEffect(function registerKeyHandlers() {
setKey('ArrowLeft', () => {
console.log(':v');
});
// eslint-disable-next-line
}, []);
// TODO: Fix tooltip position to be closer to app icon
return ( return (
<Grid container justify='center'> <Grid container alignItems='center' direction='row'>
<Grid container item> {items &&
{items && items.length &&
items.length && items.map((item) => (
items.map((item) => ( <Grid
<Tooltip item
arrow xs={xs}
key={item.id} key={item.id}
title={t(item.nameLocale)} alignItems='center'
placement='top' justify='center'
classes={{ tooltip: classes.tooltip }} >
TransitionComponent={Zoom} <Box textAlign='center'>
> <Link to={item.path}>
<Grid
key={item.id}
item
className={classes.item}
component={Link}
to={item.path}
>
<Component {...item} /> <Component {...item} />
</Grid> </Link>
</Tooltip> </Box>
))} </Grid>
</Grid> ))}
</Grid> </Grid>
); );
}; };
+58
View File
@@ -0,0 +1,58 @@
import { Button, ButtonProps, fade, makeStyles } from '@material-ui/core';
import React from 'react';
type StatusButtonStyleColor = 'success' | 'error' | 'warning' | 'info';
interface IStatusButtonStyleProps {
color: StatusButtonStyleColor;
}
const useStyles = makeStyles(
(theme) => ({
root: {
color: ({ color }: IStatusButtonStyleProps) => theme.palette[color].main,
'&:hover': {
backgroundColor: ({ color }: IStatusButtonStyleProps) =>
fade(theme.palette[color].light, theme.palette.action.hoverOpacity),
},
},
outlined: {
border: ({ color }: IStatusButtonStyleProps) =>
`1px solid ${fade(theme.palette[color].main, 0.5)}`,
'&:hover': {
border: ({ color }: IStatusButtonStyleProps) =>
`1px solid ${theme.palette[color].main}`,
},
'&$disabled': {
border: `1px solid ${theme.palette.action.disabled}`,
},
},
contained: {
color: ({ color }: IStatusButtonStyleProps) =>
theme.palette[color].contrastText,
backgroundColor: ({ color }: IStatusButtonStyleProps) =>
theme.palette[color].main,
'&:hover': {
backgroundColor: ({ color }: IStatusButtonStyleProps) =>
theme.palette[color].dark,
},
},
}),
{ name: 'MuiButton' }
);
export const StatusButton = ({
color = 'info',
variant,
className,
...props
}: Omit<ButtonProps, 'color'> & { color: StatusButtonStyleColor }) => {
const classes = useStyles({ color });
return (
<Button
variant={variant}
className={`${classes.root} ${classes[variant] || ''} ${className}`}
{...props}
/>
);
};
@@ -0,0 +1,60 @@
import {
fade,
IconButton,
IconButtonProps,
makeStyles,
} from '@material-ui/core';
import React from 'react';
type StatusButtonStyleColor = 'success' | 'error' | 'warning' | 'info';
interface IStatusButtonStyleProps {
color: StatusButtonStyleColor;
}
const useStyles = makeStyles(
(theme) => ({
root: {
color: ({ color }: IStatusButtonStyleProps) =>
theme.palette[color].contrastText,
backgroundColor: ({ color }: IStatusButtonStyleProps) =>
theme.palette[color].main,
'&:hover': {
backgroundColor: ({ color }: IStatusButtonStyleProps) =>
theme.palette[color].light,
},
},
outlined: {
border: ({ color }: IStatusButtonStyleProps) =>
`1px solid ${fade(theme.palette[color].main, 0.5)}`,
'&:hover': {
border: ({ color }: IStatusButtonStyleProps) =>
`1px solid ${theme.palette[color].main}`,
},
'&$disabled': {
border: `1px solid ${theme.palette.action.disabled}`,
},
},
contained: {
color: ({ color }: IStatusButtonStyleProps) =>
theme.palette[color].contrastText,
backgroundColor: ({ color }: IStatusButtonStyleProps) =>
theme.palette[color].main,
'&:hover': {
backgroundColor: ({ color }: IStatusButtonStyleProps) =>
theme.palette[color].dark,
},
},
}),
{ name: 'MuiIconButton' }
);
export const StatusIconButton = ({
color = 'info',
size,
className,
...props
}: Omit<IconButtonProps, 'color'> & { color: StatusButtonStyleColor }) => {
const classes = useStyles({ color });
return <IconButton className={`${classes.root} ${className}`} size={size} {...props} />;
};
+7 -3
View File
@@ -1,6 +1,6 @@
import events from '../utils/events'; import events from '../utils/events';
import { ICall } from '../../phone/src/common/typings/call'; import { ICall } from '../../phone/src/common/typings/call';
import {phoneCallStartAnim, phoneCallEndAnim} from './functions'; import { phoneCallStartAnim, phoneCallEndAnim } from './functions';
const exp = (global as any).exports; const exp = (global as any).exports;
@@ -21,6 +21,7 @@ onNet(
app: 'CALL', app: 'CALL',
method: 'setCaller', method: 'setCaller',
data: { data: {
active: true,
transmitter: transmitter, transmitter: transmitter,
receiver: receiver, receiver: receiver,
isTransmitter: isTransmitter, isTransmitter: isTransmitter,
@@ -41,12 +42,13 @@ onNet(
events.PHONE_CALL_WAS_ACCEPTED, events.PHONE_CALL_WAS_ACCEPTED,
(channelId: number, currentCall: ICall, isTransmitter: boolean) => { (channelId: number, currentCall: ICall, isTransmitter: boolean) => {
exp['mumble-voip'].SetCallChannel(channelId); exp['mumble-voip'].SetCallChannel(channelId);
phoneCallStartAnim() // Trigger call animation only if the call was accepted. phoneCallStartAnim(); // Trigger call animation only if the call was accepted.
SendNuiMessage( SendNuiMessage(
JSON.stringify({ JSON.stringify({
app: 'CALL', app: 'CALL',
method: 'setCaller', method: 'setCaller',
data: { data: {
active: true,
transmitter: currentCall.transmitter, transmitter: currentCall.transmitter,
receiver: currentCall.receiver, receiver: currentCall.receiver,
isTransmitter: isTransmitter, isTransmitter: isTransmitter,
@@ -75,13 +77,14 @@ onNet(events.PHONE_CALL_WAS_REJECTED, () => {
receiver: null, receiver: null,
isTransmitter: null, isTransmitter: null,
accepted: false, accepted: false,
active: false,
}, },
}) })
); );
}); });
onNet(events.PHONE_CALL_SEND_HANGUP_ANIM, () => { onNet(events.PHONE_CALL_SEND_HANGUP_ANIM, () => {
phoneCallEndAnim() phoneCallEndAnim();
}); });
RegisterNuiCallbackType(events.PHONE_END_CALL); // Fires when ending an ACTIVE call RegisterNuiCallbackType(events.PHONE_END_CALL); // Fires when ending an ACTIVE call
@@ -104,6 +107,7 @@ onNet(events.PHONE_CALL_WAS_ENDED, () => {
receiver: null, receiver: null,
isTransmitter: null, isTransmitter: null,
accepted: false, accepted: false,
active: false,
}, },
}) })
); );
+36 -62
View File
@@ -1,51 +1,12 @@
import config from '../utils/config'; import config from '../utils/config';
import events from '../utils/events'; import events from '../utils/events';
import {phoneCloseAnim, phoneOpenAnim, removePhoneProp} from './functions'; import { phoneCloseAnim, phoneOpenAnim, removePhoneProp } from './functions';
let prop = 0; let prop = 0;
let isPhoneOpen = false; let isPhoneOpen = false;
let propCreated = false; let propCreated = false;
let phoneModel = 'prop_amb_phone'; // Refered to in newphoneProp function. Requires custom phone being streamed. let phoneModel = 'prop_amb_phone'; // Refered to in newphoneProp function. Requires custom phone being streamed.
/* * * * * * * * * * * * *
*
* Register Command and Keybinding
*
* * * * * * * * * * * * */
RegisterCommand(
'phone:close',
async (source: any, args: string[], raw: any) => {
await phoneCloseAnim();
SetNuiFocus(false, false);
SendNuiMessage(
JSON.stringify({
app: 'PHONE',
method: 'setVisibility',
data: false,
})
);
},
false
);
RegisterCommand(
'phone',
async () => {
//-- Toggles Phone
await Phone();
},
false
);
RegisterCommand(
'phone:open',
async () => {
await Phone();
},
false
);
RegisterKeyMapping('phone', 'Open Phone', 'keyboard', 'f1'); RegisterKeyMapping('phone', 'Open Phone', 'keyboard', 'f1');
/* * * * * * * * * * * * * /* * * * * * * * * * * * *
@@ -66,7 +27,6 @@ const showPhone = async (): Promise<void> => {
data: true, data: true,
}) })
); );
sendPhoneConfig();
SetNuiFocus(true, true); SetNuiFocus(true, true);
}; };
@@ -84,13 +44,36 @@ const hidePhone = async (): Promise<void> => {
SetNuiFocus(false, false); SetNuiFocus(false, false);
}; };
const togglePhoneVisible = async (): Promise<void> => { /* * * * * * * * * * * * *
if (isPhoneOpen) { *
* Register Command and Keybinding
*
* * * * * * * * * * * * */
RegisterCommand(
'phone:close',
async () => {
await hidePhone(); await hidePhone();
} else { },
false
);
RegisterCommand(
'phone',
async () => {
//-- Toggles Phone
await Phone();
},
false
);
RegisterCommand(
'phone:open',
async () => {
await showPhone(); await showPhone();
} },
}; false
);
/* * * * * * * * * * * * * /* * * * * * * * * * * * *
* *
@@ -99,24 +82,17 @@ const togglePhoneVisible = async (): Promise<void> => {
* * * * * * * * * * * * */ * * * * * * * * * * * * */
async function Phone(): Promise<void> { async function Phone(): Promise<void> {
fetchOnInitialize() fetchOnInitialize();
if (config.PhoneAsItem) { if (config.PhoneAsItem) {
// TODO: Do promise callback here // TODO: Do promise callback here
// const hasPhoneItem = await emitNetPromise('phone:hasPhoneItem') // const hasPhoneItem = await emitNetPromise('phone:hasPhoneItem')
// if (!hasPhoneItem) return // if (!hasPhoneItem) return
return await togglePhoneVisible();
} }
await togglePhoneVisible(); if (isPhoneOpen) {
} await hidePhone();
} else {
function sendPhoneConfig() { await showPhone();
SendNuiMessage( }
JSON.stringify({
app: 'PHONE',
method: 'phoneConfig',
data: config,
})
);
} }
AddEventHandler('onResourceStop', function (resource: string) { AddEventHandler('onResourceStop', function (resource: string) {
@@ -144,7 +120,6 @@ onNet('phone:sendCredentials', (number: string) => {
); );
}); });
// DO NOT CHANGE THIS EITHER, PLEASE - CHIP // DO NOT CHANGE THIS EITHER, PLEASE - CHIP
/* * * * * * * * * * * * * /* * * * * * * * * * * * *
@@ -157,7 +132,6 @@ function fetchOnInitialize() {
emitNet(events.CONTACTS_GET_CONTACTS); emitNet(events.CONTACTS_GET_CONTACTS);
} }
RegisterNuiCallbackType(events.OPEN_APP_LISTINGS); RegisterNuiCallbackType(events.OPEN_APP_LISTINGS);
on(`__cfx_nui:${events.OPEN_APP_LISTINGS}`, (data: any, cb: Function) => { on(`__cfx_nui:${events.OPEN_APP_LISTINGS}`, (data: any, cb: Function) => {
emitNet(events.SELLOUT_FETCH_LISTING); emitNet(events.SELLOUT_FETCH_LISTING);
@@ -191,7 +165,7 @@ on(`__cfx_nui:${events.OPEN_APP_DAILER}`, (data: any, cb: Function) => {
RegisterNuiCallbackType('phone:close'); RegisterNuiCallbackType('phone:close');
on(`__cfx_nui:phone:close`, async (data: any, cb: Function) => { on(`__cfx_nui:phone:close`, async (data: any, cb: Function) => {
await Phone(); await hidePhone();
cb(); cb();
}); // Called for when the phone is closed via the UI. }); // Called for when the phone is closed via the UI.
+1 -1
View File
@@ -1,6 +1,6 @@
-- comment this out if your server has a different table/location for phone_number -- comment this out if your server has a different table/location for phone_number
-- or if it already exists in the users table -- or if it already exists in the users table
ALTER TABLE `users` ADD COLUMN `phone_number` VARCHAR(20) NULL DEFAULT NULL; ALTER TABLE `users` ADD COLUMN `phone_number` VARCHAR(20) DEFAULT NULL;
INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES ('phone', 'Phone', 1, 0, 1); INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES ('phone', 'Phone', 1, 0, 1);
INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES ('dphone', 'Destroyed Phone', 1, 0, 1); INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES ('dphone', 'Destroyed Phone', 1, 0, 1);
+1 -1
View File
@@ -18,7 +18,7 @@ interface ContactId {
} }
async function fetchAllContacts(identifier: string): Promise<Contacts[]> { async function fetchAllContacts(identifier: string): Promise<Contacts[]> {
const query = 'SELECT * FROM npwd_phone_contacts WHERE identifier = ?'; const query = 'SELECT * FROM npwd_phone_contacts WHERE identifier = ? ORDER BY display ASC';
const [results] = await pool.query(query, [identifier]); const [results] = await pool.query(query, [identifier]);
const contacts = <Contacts[]>results; const contacts = <Contacts[]>results;
return contacts; return contacts;
+18 -17
View File
@@ -35,26 +35,27 @@ function getRandomPhoneNumber() {
// The numbers inside {} in replace() can be changed to how many digits you want on each side of the dash. // The numbers inside {} in replace() can be changed to how many digits you want on each side of the dash.
// Example: 123-4567 // Example: 123-4567
} }
mainLogger.verbose(`Getting random number: ${randomNumber}`); mainLogger.verbose(`Getting random number: ${randomNumber}`);
return randomNumber; return randomNumber;
} }
async function generatePhoneNumber(identifier: string) { async function generatePhoneNumber(identifier: string) {
const _identifier = identifier; if (!await usePhoneNumber(identifier)) {
let phoneNumber = await usePhoneNumber(_identifier); let existingId;
let id = await getIdentifierByPhoneNumber(phoneNumber); let newNumber;
do {
do { newNumber = getRandomPhoneNumber();
if (!phoneNumber) { try {
phoneNumber = await getRandomPhoneNumber(); existingId = await getIdentifierByPhoneNumber(newNumber)
const query = 'UPDATE users SET phone_number = ? WHERE identifier = ?'; } catch(e) {
await pool.query(query, [phoneNumber, _identifier]); existingId = false
} else { }
break; } while(existingId);
} mainLogger.verbose(`Inserting number into Database: ${newNumber}`);
} while (id); const query = 'UPDATE users SET phone_number = ? WHERE identifier = ?';
await pool.query(query, [newNumber, identifier]);
}
} }
async function getCredentials(identifier: string): Promise<string> { async function getCredentials(identifier: string): Promise<string> {
@@ -65,11 +66,11 @@ async function getCredentials(identifier: string): Promise<string> {
return number[0].phone_number; return number[0].phone_number;
} }
on('playerConnecting', async () => { onNet('esx:playerLoaded', async (playerId: number, xPlayer: any) => {
const _source = getSource() const _source = getSource()
try { try {
const identifier = getIdentifier(_source); const identifier = xPlayer.identifier;
await generatePhoneNumber(identifier) await generatePhoneNumber(identifier);
} catch(e) { } catch(e) {
mainLogger.error(`Failed to generate a phone number, ${e.message}`, { mainLogger.error(`Failed to generate a phone number, ${e.message}`, {
source: _source, source: _source,
+2 -2
View File
@@ -22,8 +22,8 @@ async function getPhotosByIdentifier(identifier: string): Promise<IPhoto[]> {
async function deletePhoto(photo: IPhoto, identifier: string) { async function deletePhoto(photo: IPhoto, identifier: string) {
const query = const query =
'DELETE FROM npwd_phone_gallery WHERE id = ? AND identifier = ?'; 'DELETE FROM npwd_phone_gallery WHERE image = ? AND identifier = ?';
await pool.query(query, [photo.id, identifier]); await pool.query(query, [photo.image, identifier]);
} }
onNet(events.CAMERA_UPLOAD_PHOTO, async (image: string) => { onNet(events.CAMERA_UPLOAD_PHOTO, async (image: string) => {