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 './i18n';
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 { ThemeProvider, Slide } from '@material-ui/core';
import { useInitKeyboard } from './os/keyboard/hooks/useKeyboard';
import { Slide } from '@material-ui/core';
import { useKeyboardService } from './os/keyboard/hooks/useKeyboardService';
import { NotificationBar } from './os/notifications/components/NotificationBar';
import { Navigation } from './os/navigation-bar/components/Navigation';
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 { usePhotoService } from './apps/camera/hooks/usePhotoService';
import { useSettings } from './apps/settings/hooks/useSettings';
import { useCallService } from './modal/hooks/useCallService';
import { useModal } from './modal/hooks/useModal';
import { useCallService } from './os/call/hooks/useCallService';
import { useDialService } from './apps/dialer/hooks/useDialService';
import InjectDebugData from './os/debug/InjectDebugData';
import { usePhoneVisibility } from './os/phone/hooks/usePhoneVisibility';
import { usePhoneTheme } from './os/phone/hooks/usePhoneTheme';
import { Snackbar } from './ui/components/Snackbar';
import { NotificationAlert } from './os/notifications/components/NotificationAlert';
import { useCallModal } from './os/call/hooks/useCallModal';
function Phone() {
const { modal } = useModal();
const { apps } = useApps();
const [settings] = useSettings();
const {
bottom,
visibility,
uncollapseNotifications,
clickEventOverride,
} = usePhoneVisibility();
useNuiService();
useKeyboardService();
usePhoneService();
useSimcardService();
useContactsService();
useTwitterService();
useInitKeyboard();
useSelloutService();
useBankService();
useMessagesService();
@@ -56,58 +48,56 @@ function Phone() {
useCallService();
useDialService();
const currentTheme = usePhoneTheme();
const { modal: callModal } = useCallModal();
const { bottom, visibility } = usePhoneVisibility();
return (
<ThemeProvider theme={currentTheme}>
<Slide direction='up' in={visibility} mountOnEnter unmountOnExit>
<div className='PhoneWrapper'>
<div>
<Slide direction='up' in={visibility}>
<div className='PhoneWrapper'>
<div>
<div
className='Phone'
style={{
transformOrigin: 'right bottom',
transform: `scale(${settings.zoom}`,
bottom,
}}
>
<div
onClick={clickEventOverride}
className='Phone'
className='PhoneFrame'
style={{
transformOrigin: 'right bottom',
transform: `scale(${settings.zoom}`,
bottom,
backgroundImage: `url(./media/frames/${settings.frame})`,
}}
/>
<div
id='phone'
className='PhoneScreen'
style={{
backgroundImage: `url(./media/backgrounds/${settings.wallpaper})`,
}}
>
<div
className='PhoneFrame'
style={{
backgroundImage: `url(./media/frames/${settings.frame})`,
}}
/>
<div
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} />
))}
</>
<>
<NotificationBar />
<div className='PhoneAppContainer'>
<>
<Route exact path='/' component={HomeApp} />
{callModal && (
<Route exact path='/call' component={CallModal} />
)}
<Snackbar />
</div>
<Navigation />
</>
</div>
{apps.map((App) => (
<App.Route key={App.id} />
))}
</>
<NotificationAlert />
<Snackbar />
</div>
<Navigation />
</>
</div>
</div>
</div>
</Slide>
</ThemeProvider>
</div>
</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 { SvgIcon } from '@material-ui/core';
import { SvgIcon, SvgIconProps } from '@material-ui/core';
export const CalculatorIcon = ({ ...props }) => {
export const CalculatorIcon = ({ ...props}: SvgIconProps) => {
return (
<SvgIcon {...props}>
<svg
@@ -16,7 +16,7 @@ InjectDebugData([
image: 'https://i.imgur.com/OO8wx6Z.jpg',
},
{
id: 1,
id: 2,
image: 'https://i.imgur.com/pqGBiST.jpg',
},
],
@@ -27,12 +27,12 @@ export const GalleryModal = () => {
history.push(referal);
};
const handleDeletePhoto = useCallback(() => {
const handleDeletePhoto = () => {
Nui.send('photo:deletePhoto', {
id: meta.id,
image: meta.image,
});
history.push(referal);
}, [history, meta.id, referal]);
};
const handleSharePhoto = useCallback(() => {
setShareOpen(meta);
@@ -42,7 +42,11 @@ export const GalleryModal = () => {
return (
<>
<ShareModal referal={referal} meta={shareOpen} onClose={() => setShareOpen(null)} />
<ShareModal
referal={referal}
meta={shareOpen}
onClose={() => setShareOpen(null)}
/>
<Paper className={classes.modal}>
<div className={shareOpen ? classes.backgroundModal : null} />
<Button onClick={_handleClose}>
@@ -45,7 +45,7 @@ InjectDebugData([
{
id: 3,
display: 'Chip',
number: '417-8792',
number: '777-7777',
},
],
},
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import {
Avatar as MuiAvatar,
Box,
@@ -13,12 +13,18 @@ import { useContacts } from '../../hooks/useContacts';
import Nui from '../../../../os/nui-events/utils/Nui';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import LogDebugEvent from '../../../../os/debug/LogDebugEvents';
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
interface ContactInfoRouteParams {
mode: string;
id: string;
}
interface ContactInfoRouteQuery {
addNumber?: string;
referal?: string;
}
const useStyles = makeStyles((theme: Theme) => ({
root: {
height: '100%',
@@ -54,6 +60,7 @@ const ContactsInfoPage = () => {
const { getContact } = useContacts();
const { id } = useParams<ContactInfoRouteParams>();
const { addNumber, referal } = useQueryParams<ContactInfoRouteQuery>({ referal: '/contacts' });
const contact = getContact(parseInt(id));
@@ -64,6 +71,12 @@ const ContactsInfoPage = () => {
const { t } = useTranslation();
useEffect(() => {
if (addNumber) {
setNumber(addNumber);
}
}, [addNumber]);
const handleContactAdd = () => {
LogDebugEvent({
action: 'Handling Contact Add',
@@ -75,7 +88,7 @@ const ContactsInfoPage = () => {
number,
avatar,
});
history.goBack();
history.replace(referal);
};
const handleContactSave = () => {
@@ -113,6 +126,7 @@ const ContactsInfoPage = () => {
<div className={classes.listContainer}>
<MuiAvatar className={classes.avatar} src={avatar} />
<TextField
autoFocus
className={classes.input}
value={name}
onChange={(e) => setName(e.target.value)}
@@ -4,7 +4,7 @@ import { makeStyles, Theme } from '@material-ui/core/styles';
const useStyles = makeStyles((theme: Theme) => ({
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 InjectDebugData from '../../../os/debug/InjectDebugData';
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([
{
@@ -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 { makeStyles, Theme } from '@material-ui/core/styles';
import PhoneIcon from '@material-ui/icons/Phone';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import { DialInputCtx } from '../context/InputContext';
import Nui from '../../../os/nui-events/utils/Nui';
import { useHistory } from 'react-router-dom';
const useStyles = makeStyles((theme: Theme) => ({
root: {
@@ -26,8 +28,9 @@ const useStyles = makeStyles((theme: Theme) => ({
export const DialerInput = () => {
const classes = useStyles();
const history = useHistory();
const { inputVal } = useContext(DialInputCtx)
const { inputVal } = useContext(DialInputCtx);
const handleCall = (number: string) => {
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 (
<Box component={Paper} className={classes.root}>
<InputBase
@@ -42,8 +49,11 @@ export const DialerInput = () => {
className={classes.input}
value={inputVal}
/>
<IconButton color='primary' className={classes.iconBtn}>
<PhoneIcon fontSize="large" onClick={() => handleCall(inputVal)} />
</IconButton>
<IconButton className={classes.iconBtn}>
<PhoneIcon onClick={() => handleCall(inputVal)} />
<PersonAddIcon fontSize="large" onClick={() => handleNewContact(inputVal)} />
</IconButton>
</Box>
);
@@ -9,10 +9,10 @@ import HistoryIcon from '@material-ui/icons/History';
const useStyles = makeStyles((theme: Theme) => ({
root: {
width: '100%',
backgroundColor: theme.palette.background.default,
backgroundColor: theme.palette.background.paper,
},
icon: {
color: '#43a047',
color: theme.palette.primary.main,
},
}));
@@ -1,7 +1,8 @@
import React from 'react';
import ListItemText from '@material-ui/core/ListItemText';
import PhoneCallbackIcon from '@material-ui/icons/PhoneCallback';
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 { ListItem } from '../../../../ui/components/ListItem';
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 dayjs from 'dayjs';
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 }) => {
const { number } = useSimcard();
const { getDisplayByNumber } = useContacts();
const classes = useStyles();
const history = useHistory();
const { t } = useTranslation();
const handleCall = (phoneNumber) => {
@@ -23,8 +40,22 @@ export const DialerHistory = ({ calls }) => {
});
};
if (!calls) {
return <p>Things are loading or arent here at all</p>;
if (!calls?.length) {
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 (
@@ -34,27 +65,59 @@ export const DialerHistory = ({ calls }) => {
<ListItem
key={call.id}
divider
button
onClick={() => handleCall(call.receiver)}
>
<ListItemIcon>
{<PhoneForwardedIcon className={classes.callForward} />}
</ListItemIcon>
<ListItemText
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
key={call.id}
divider
button
onClick={() => handleCall(call.transmitter)}
>
<ListItemIcon>
{<PhoneCallbackIcon className={classes.callBack} />}
</ListItemIcon>
<ListItemText
primary={getDisplayByNumber(call.transmitter)}
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>
)
)}
+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 = {
history: atom({
key: 'dialHistory',
default: null,
default: [],
}),
};
@@ -5,7 +5,7 @@ interface ICallUI {
history: ICall[];
}
export const useDialHistory = (): ICallUI => {
export const useDialHistory = (): ICallUI[] => {
const history = useRecoilValue(dialState.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 { AppContent } from '../../../ui/components/AppContent';
@@ -6,12 +6,17 @@ import { useApp } from '../../../os/apps/hooks/useApps';
import { useExample } from '../hooks/useExample';
import { ExampleThemeProvider } from '../providers/ExampleThemeProvider';
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 = () => {
// calling the example hook, and we assign the value to a variable
const exampleString = useExample();
const example = useApp('EXAMPLE');
const [soundName, setSound] = useState('pixel.ogg');
const { play, playing, stop } = useSound('media/ringtones/' + soundName);
return (
<ExampleThemeProvider>
<AppWrapper>
@@ -21,6 +26,12 @@ export const ExampleApp = () => {
<Button color='primary'>{example.id}</Button>
{/* Here we are using the value in a h3 tag */}
<h3>{exampleString}</h3>
<IconButton onClick={() => (playing ? stop() : play())}>
{playing ? <StopIcon /> : <PlayIcon />}
</IconButton>
<Button onClick={() => setSound('marimba.ogg')}>
Change sound on the fly
</Button>
</AppContent>
</AppWrapper>
</ExampleThemeProvider>
+2 -2
View File
@@ -8,8 +8,8 @@ export const HomeApp = () => {
const { apps } = useApps();
return (
<AppWrapper>
<Box width='100%' mt={6} px={1}>
{apps && <GridMenu items={apps} />}
<Box component="div" mt={6} px={1}>
{apps && <GridMenu xs={3} items={apps} />}
</Box>
</AppWrapper>
);
@@ -12,9 +12,11 @@ const useStyles = makeStyles((theme) => ({
mySms: {
float: 'right',
margin: theme.spacing(1),
padding: '6px 12px',
padding: '6px 16px',
height: 'auto',
width: '80%',
width: 'auto',
minWidth: '60%',
maxWidth: '85%',
background: theme.palette.background.default,
color: theme.palette.text.primary,
borderRadius: '20px',
@@ -24,7 +26,9 @@ const useStyles = makeStyles((theme) => ({
float: 'left',
margin: theme.spacing(1),
padding: '6px 12px',
width: '80%',
width: 'auto',
minWidth: '60%',
maxWidth: '85%',
height: 'auto',
background: theme.palette.primary.light,
color: theme.palette.getContrastText(theme.palette.primary.light),
@@ -62,7 +66,7 @@ export const MessageBubble = ({
<div>{message.message}</div>
)}
</Box>
<Box textAlign='right'>
<Box>
<Typography variant='subtitle1' color='secondary'>
{isGroupChat && !message.isMine
? 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 { useApp } from '../../os/apps/hooks/useApps';
import NoteList from './list/NoteList';
import { useNotes } from './hooks/useNotes';
import { NoteModal } from './modal/NoteModal';
import { Fab } from '@material-ui/core';
import AddIcon from '@material-ui/icons/Add';
import { useNoteModal } from './hooks/useNoteModal';
import { useNoteDetail } from './hooks/useNoteDetail';
import useStyles from './notes.styles';
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([
{
@@ -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 { yellow } from '@material-ui/core/colors';
import useStyles from './notes.styles';
import { Paper } from '@material-ui/core';
import { makeStyles, Paper } from '@material-ui/core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
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 classes = useStyles();
return (
<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>
);
};
@@ -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 { useNoteModal } from '../hooks/useNoteModal';
import { List, ListItem, ListItemText } from '@material-ui/core';
import { useNoteDetail } from '../hooks/useNoteDetail';
import { useNotes } from '../hooks/useNotes';
import { useHistory } from 'react-router-dom';
// add search bar later
// TODO: Add interface for note
const NoteList = ({ notes }) => {
const { setNoteModal } = useNoteModal();
const NoteList = () => {
const history = useHistory();
const { notes } = useNotes();
const { setDetail } = useNoteDetail();
const handleNoteModal = (note) => {
setNoteModal(true);
setDetail(note);
history.push('/notes/detail');
};
return (
+121 -89
View File
@@ -1,41 +1,39 @@
import { Button, TextField, Slide } from '@material-ui/core';
import React, { useState } from 'react';
import {
Button,
TextField,
Slide,
Paper,
Typography,
Container,
CircularProgress,
Box,
} from '@material-ui/core';
import React from 'react';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import { useNoteModal } from '../hooks/useNoteModal';
import { useNoteDetail } from '../hooks/useNoteDetail';
import useStyles from './modal.styles';
import '../NotesApp.css';
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 = () => {
const { noteModal, setNoteModal } = useNoteModal();
const classes = useStyles();
const history = useHistory();
const { t } = useTranslation();
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 = () => {
setDetail(null);
setNoteModal(false);
onClose();
};
const handleNoteSave = () => {
Nui.send('phone:addNote', {
title,
content,
});
Nui.send('phone:addNote', detail);
setDetail(null);
setNoteModal(false);
setTitle('')
setContent('')
onClose();
};
const handleDeleteNote = () => {
@@ -44,78 +42,112 @@ export const NoteModal = () => {
id,
});
setDetail(null);
setNoteModal(false);
onClose();
};
const handleUpdateNote = () => {
Nui.send('phone:updateNote', {
id: detail.id,
title,
content,
});
Nui.send('phone:updateNote', detail);
setDetail(null);
setNoteModal(false);
onClose();
};
return (
<div className={noteModal ? classes.modalRoot : classes.modalHide}>
<Slide direction='left' in={noteModal} mountOnEnter unmountOnExit>
<div>
<Button className={classes.closeButton} onClick={_handleClose}>
<ArrowBackIcon fontSize='large' />
</Button>
<div id='notes-modal' className={classes.noteContainer}>
<TextField
className={classes.input}
rowsMax={1}
placeholder='Title'
inputProps={{
className: classes.inputPropsTitle,
maxLength: 25
}}
fullWidth
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<TextField
className={classes.input}
inputProps={{
className: classes.inputPropsContent,
maxLength: 250,
}}
placeholder='Content'
multiline
fullWidth
rows={19}
variant='outlined'
value={content}
onChange={(e) => setContent(e.target.value)}
/>
<p style={{ color: "#fff" }}>{content.length}/250</p>
{!detail &&(
<Button disabled={title.length > 0 ? false : true} className={classes.saveButton} onClick={handleNoteSave}>
Save
</Button>
)}
{detail && (
<Button
className={classes.updateButton}
onClick={handleUpdateNote}
>
Update
</Button>
)}
{detail && (
<Button
className={classes.deleteButton}
onClick={handleDeleteNote}
>
Delete
</Button>
)}
</div>
</div>
</Slide>
</div>
<Slide direction='left' in={!!detail}>
<Paper className={classes.modalRoot}>
{!detail ? (
<CircularProgress />
) : (
<Container>
<Box>
<Box py={2}>
<Button
color='primary'
size='large'
startIcon={<ArrowBackIcon fontSize='large' />}
onClick={_handleClose}
>
{t('APPS_NOTES')}
</Button>
</Box>
<TextField
className={classes.input}
rowsMax={1}
label={t('GENERIC_TITLE')}
inputProps={{
className: classes.inputPropsTitle,
maxLength: 25,
}}
fullWidth
value={detail.title}
onChange={(e) =>
setDetail((d) => ({ ...d, title: e.target.value }))
}
/>
<TextField
className={classes.input}
inputProps={{
className: classes.inputPropsContent,
maxLength: 250,
}}
label={t('GENERIC_CONTENT')}
multiline
fullWidth
rows={16}
variant='outlined'
value={detail.content}
onChange={(e) =>
setDetail((d) => ({ ...d, content: e.target.value }))
}
/>
<Typography paragraph>{detail.content.length}/250</Typography>
{!detail.id ? (
<>
<Box display="inline" p={1}>
<Button
color='primary'
variant='contained'
disabled={detail.title.length > 0 ? false : true}
onClick={handleNoteSave}
>
{t('GENERIC_SAVE')}
</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: {
zIndex: 20,
position: 'absolute',
height: '100%',
height: '99%',
width: '100%',
background: '#232323',
},
modalHide: {
display: 'none',
},
closeButton: {
width: '10%',
position: 'absolute',
top: 10,
left: 0,
},
noteContainer: {
width: '90%',
marginTop: 80,
margin: '0 auto',
background: theme.palette.background.default,
},
input: {
marginBottom: 20,
@@ -30,19 +16,7 @@ const useStyles = makeStyles((theme) => ({
},
inputPropsContent: {
fontSize: 20,
},
saveButton: {
background: '#f9a825',
padding: '10px 30px',
},
updateButton: {
background: '#f9a825',
padding: '10px 30px',
marginRight: '8px',
},
deleteButton: {
background: '#c62828',
padding: '10px 30px',
lineHeight: 1.2,
},
}));
-9
View File
@@ -1,15 +1,6 @@
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({
header: {
width: '100%',
display: 'flex',
flexFlow: 'row nowrap',
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
height: '60px',
},
backgroundModal: {
background: 'black',
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 = {
palette: {
primary: {
main: '#f44336',
dark: '#b3251b',
light: 'f87f76',
contrastText: common.black
main: SELLOUT_APP_PRIMARY_COLOR,
dark: red[700],
light: red[200],
contrastText: SELLOUT_APP_TEXT_COLOR
}
}
}
+100 -94
View File
@@ -20,100 +20,6 @@ import { useProfile } from '../hooks/useProfile';
import ProfilePrompt from './profile/ProfilePrompt';
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(() => ({
backgroundModal: {
background: 'black',
@@ -186,3 +92,103 @@ export const TwitterApp = () => {
</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 { useTweets } from '../../hooks/useTweets';
import { useTwitterNotifications } from '../../hooks/useTwitterNotifications';
import TweetList from './TweetList';
export function TweetListContainer() {
const { tweets } = useTweets();
const { setUnreadCount } = useTwitterNotifications();
useEffect(() => {
Nui.send('phone:fetchTweets', {});
}, []);
useEffect(() => {
if (tweets?.length) {
setUnreadCount(0);
}
}, [setUnreadCount, tweets]);
return <TweetList tweets={tweets} />;
}
+3 -3
View File
@@ -37,8 +37,8 @@ export const twitterState = {
key: 'updateProfileSuccess',
default: null,
}),
notification: atom({
key: 'notification',
default: null,
unreadTweetsCount: atom({
key: 'unreadTweetsCount',
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 { APP_TWITTER } from '../utils/constants';
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 { useTwitterNotifications } from './useTwitterNotifications';
/**
* Perform all necessary processing/transforms from the raw database
@@ -33,23 +30,8 @@ function processTweet(tweet) {
* there and have moved that logic here instead.
*/
export const useTwitterService = () => {
const { t } = useTranslation();
const { addNotification } = useNotifications();
const { addAlert } = useSnackbar()
const { icon, notificationIcon } = useApp('TWITTER');
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 { setNotification } = useTwitterNotifications();
const setProfile = useSetRecoilState(twitterState.profile);
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 }>();
*/
export function useQueryParams<T = Record<string, string>>() {
return qs.parse(useLocation().search, { ignoreQueryPrefix: true }) as T &
Partial<ParsedQs>;
export function useQueryParams<T = Record<string, string>>(
defaultValues: T = null
) {
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 {
active: boolean;
accepted: boolean;
isTransmitter: boolean;
transmitter: string;
+1 -1
View File
@@ -44,7 +44,7 @@
"palette": {
"type": "dark",
"primary": {
"main": "#a6d4fa"
"main": "#a6d4fa"
},
"background": {
"paper": "#1c1c1c",
+2 -8
View File
@@ -6,10 +6,8 @@ import { RecoilRoot } from 'recoil';
import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing';
import './main.css';
import Phone from './Phone';
import PhoneConfig from './config/default.json';
import SnackbarProvider from './ui/providers/SnackbarProvider';
import { NotificationsProvider } from './os/notifications/providers/NotificationsProvider';
import { PhoneContainer } from './PhoneContainer';
// Enable Sentry when config setting is true
if (PhoneConfig.SentryErrorMetrics) {
@@ -27,11 +25,7 @@ if (PhoneConfig.SentryErrorMetrics) {
ReactDOM.render(
<HashRouter>
<RecoilRoot>
<SnackbarProvider>
<NotificationsProvider>
<Phone />
</NotificationsProvider>
</SnackbarProvider>
<PhoneContainer />
</RecoilRoot>
</HashRouter>,
document.getElementById('root')
+13 -1
View File
@@ -17,6 +17,14 @@
"APPS_SELLOUT": "Market",
"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_SETTINGS_OPTIONS_WALLPAPER": "Wallpaper",
"APPS_SETTINGS_OPTIONS_FRAME": "Frame",
@@ -48,6 +56,7 @@
"APPS_TWITTER_TIME_HOURS": "h",
"APPS_TWITTER_TIME_DAYS": "d",
"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_ACCOUNT_LINK": "Account",
@@ -110,6 +119,9 @@
"GENERIC_SAVE": "Save",
"GENERIC_UPDATE": "Update",
"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,
common,
grey,
green,
purple,
yellow,
red,
} from '@material-ui/core/colors';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
@@ -35,6 +32,7 @@ import { SelloutApp } from '../../../apps/sellout/components/SelloutApp';
import { NotesApp } from '../../../apps/notes/NotesApp';
import CameraApp from '../../../apps/camera/components/CameraApp';
import { AppRoute } from '../components/AppRoute';
import {
MESSAGES_APP_PRIMARY_COLOR,
MESSAGES_APP_TEXT_COLOR,
@@ -43,6 +41,9 @@ import {
CONTACTS_APP_PRIMARY_COLOR,
CONTACTS_APP_TEXT_COLOR,
} 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 {
id: string;
@@ -59,17 +60,17 @@ export const APPS: IAppConfig[] = [
{
id: 'DIALER',
nameLocale: 'APPS_DIALER',
icon: <FontAwesomeIcon icon={faPhoneAlt} size='xs' />,
icon: <FontAwesomeIcon icon={faPhoneAlt} />,
notificationIcon: <FontAwesomeIcon icon={faPhoneAlt} size='xs' />,
backgroundColor: green[600],
color: common.white,
backgroundColor: DIALER_APP_PRIMARY_COLOR,
color: DIALER_APP_TEXT_COLOR,
path: '/phone',
Route: () => <AppRoute id='DIALER' path='/phone' component={DialerApp} />,
},
{
id: 'MESSAGES',
nameLocale: 'APPS_MESSAGES',
icon: <MessageIcon fontSize='default' />,
icon: <MessageIcon fontSize="large" />,
notificationIcon: <MessageIcon fontSize='small' />,
backgroundColor: MESSAGES_APP_PRIMARY_COLOR,
color: MESSAGES_APP_TEXT_COLOR,
@@ -81,7 +82,7 @@ export const APPS: IAppConfig[] = [
{
id: 'CONTACTS',
nameLocale: 'APPS_CONTACTS',
icon: <ContactsIcon />,
icon: <ContactsIcon fontSize="large" />,
notificationIcon: <ContactsIcon fontSize='small' />,
backgroundColor: CONTACTS_APP_PRIMARY_COLOR,
color: CONTACTS_APP_TEXT_COLOR,
@@ -93,7 +94,7 @@ export const APPS: IAppConfig[] = [
{
id: 'CALCULATOR',
nameLocale: 'APPS_CALCULATOR',
icon: <CalculatorIcon />,
icon: <CalculatorIcon fontSize="large" />,
notificationIcon: <CalculatorIcon fontSize='small' />,
backgroundColor: purple[500],
color: grey[50],
@@ -105,7 +106,7 @@ export const APPS: IAppConfig[] = [
{
id: 'SETTINGS',
nameLocale: 'APPS_SETTINGS',
icon: <SettingsIcon />,
icon: <SettingsIcon fontSize="large" />,
notificationIcon: <SettingsIcon fontSize='small' />,
backgroundColor: '#383838',
color: grey[50],
@@ -117,7 +118,7 @@ export const APPS: IAppConfig[] = [
{
id: 'BANK',
nameLocale: 'APPS_BANK',
icon: <FontAwesomeIcon icon={faWonSign} size='xs' />,
icon: <FontAwesomeIcon icon={faWonSign} />,
notificationIcon: <FontAwesomeIcon icon={faWonSign} size='xs' />,
backgroundColor: blue[900],
color: common.white,
@@ -127,7 +128,7 @@ export const APPS: IAppConfig[] = [
{
id: 'TWITTER',
nameLocale: 'APPS_TWITTER',
icon: <FontAwesomeIcon icon={faTwitter} fixedWidth size='xs' />,
icon: <FontAwesomeIcon icon={faTwitter} fixedWidth />,
notificationIcon: <FontAwesomeIcon icon={faTwitter} fixedWidth size='xs' />,
backgroundColor: blue[600],
color: common.white,
@@ -141,8 +142,8 @@ export const APPS: IAppConfig[] = [
nameLocale: 'APPS_SELLOUT',
icon: <FontAwesomeIcon icon={faAd} fixedWidth />,
notificationIcon: <FontAwesomeIcon icon={faAd} fixedWidth size='xs' />,
backgroundColor: red[500],
color: common.white,
backgroundColor: SELLOUT_APP_PRIMARY_COLOR,
color: SELLOUT_APP_ICON_COLOR,
path: '/sellout',
Route: () => (
<AppRoute id='SELLOUT' path='/sellout' component={SelloutApp} />
@@ -155,8 +156,8 @@ export const APPS: IAppConfig[] = [
notificationIcon: (
<FontAwesomeIcon icon={faStickyNote} fixedWidth size='xs' />
),
backgroundColor: yellow[800],
color: common.white,
backgroundColor: NOTES_APP_PRIMARY_COLOR,
color: NOTES_APP_ICON_COLOR,
path: '/notes',
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%',
},
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;
}
export const useModal = (): ModalProps => {
export const useCallModal = (): ModalProps => {
const [modal, setModal] = useRecoilState(callerState.callModal);
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;
method: string;
data: any;
data: P;
}
// 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') {
for (const event of events) {
setTimeout(() => {
@@ -1,7 +1,7 @@
import { useCallback, useEffect } from 'react';
import { useCallback, useEffect, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import { atom, useSetRecoilState, useRecoilValue } from 'recoil';
import Nui from '../../nui-events/utils/Nui';
import { usePhone } from '../../phone/hooks/usePhone';
const keyboardState = {
ArrowRight: atom({
@@ -46,8 +46,9 @@ const validKeys = [
const isKeyValid = (key) => validKeys.indexOf(key) !== -1;
export const useInitKeyboard = () => {
export const useKeyboardService = () => {
const history = useHistory();
const { closePhone } = usePhone();
const getters = {
ArrowRight: useRecoilValue(keyboardState.ArrowRight),
ArrowLeft: useRecoilValue(keyboardState.ArrowLeft),
@@ -58,21 +59,26 @@ export const useInitKeyboard = () => {
Escape: useRecoilValue(keyboardState.Escape),
};
const handlers = useRef(new Map());
const setEscape = useSetRecoilState<any>(keyboardState.Escape);
const setBackspace = useSetRecoilState(keyboardState.Backspace);
useEffect(
function registerCustomKeys() {
Object.keys(getters).forEach((g) => {
handlers.current.set(g, getters[g]);
});
},
[getters]
);
useEffect(
function handleNUIKeyboardMessage() {
function onKeyUp(event) {
const { key } = event;
const callback = getters[key];
if (
isKeyValid(key) &&
callback &&
callback.handler &&
callback.handler.call
) {
return callback.handler(event);
const callback = handlers.current.get(key);
if (isKeyValid(key) && callback && callback.call) {
return callback(event);
}
}
@@ -82,35 +88,22 @@ export const useInitKeyboard = () => {
[getters]
);
const escapeHandler = useCallback(() => Nui.send('phone:close'), []);
const backspaceHandler = useCallback((event) => {
if (['input', 'textarea'].includes(event.target.nodeName.toLowerCase())) {
// Dont anything if we are typing something :)
return;
}
history.goBack();
}, [history]);
const backspaceHandler = useCallback(
(event) => {
if (['input', 'textarea'].includes(event.target.nodeName.toLowerCase())) {
// Dont anything if we are typing something :)
return;
}
history.goBack();
},
[history]
);
useEffect(
function registerDefaultHandlers() {
setEscape({ handler: escapeHandler });
setBackspace({ handler: backspaceHandler });
handlers.current.set('Escape', () => closePhone());
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 AppsIcon from '@material-ui/icons/Apps';
import RadioButtonUncheckedIcon from '@material-ui/icons/RadioButtonUnchecked';
import { useHistory } from 'react-router-dom';
import Nui from '../../nui-events/utils/Nui';
import { useHistory, useRouteMatch } from 'react-router-dom';
import { usePhone } from '../../phone/hooks/usePhone';
import { useNotifications } from '../../notifications/hooks/useNotifications';
const useStyles = makeStyles((theme) => ({
root: {
@@ -19,17 +19,18 @@ const useStyles = makeStyles((theme) => ({
}));
export const Navigation = () => {
const closePhone = () => {
console.log('Phone closed');
Nui.send('phone:close');
};
const classes = useStyles();
const history = useHistory();
const { isExact } = useRouteMatch('/');
const { closePhone } = usePhone();
const { setBarUncollapsed } = useNotifications();
return (
<BottomNavigation
className={classes.root}
onChange={(_e, value) => value()}
onChange={(_e, value) => {
setBarUncollapsed(false);
value();
}}
>
<BottomNavigationAction
label='Home'
@@ -38,12 +39,12 @@ export const Navigation = () => {
/>
<BottomNavigationAction
label='Close'
value={() => closePhone()}
value={closePhone}
icon={<RadioButtonUncheckedIcon />}
/>
<BottomNavigationAction
label='Back'
value={() => history.goBack()}
value={() => !isExact && history.goBack()}
icon={<KeyboardArrowLeftIcon />}
/>
</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 {
makeStyles,
Typography,
@@ -8,18 +8,14 @@ import {
Paper,
Box,
List,
ListItem,
ListItemText,
Divider,
ListItemAvatar,
} from '@material-ui/core';
import SignalIcon from '@material-ui/icons/SignalCellular3Bar';
import CloseIcon from '@material-ui/icons/Close';
import Battery90Icon from '@material-ui/icons/Battery90';
import ArrowDropUpIcon from '@material-ui/icons/ArrowDropUp';
import Default from '../../../config/default.json';
import { useNotifications } from '../hooks/useNotifications';
import { useHistory } from 'react-router-dom';
import { NotificationItem } from './NotificationItem';
const useStyles = makeStyles((theme) => ({
root: {
@@ -67,13 +63,16 @@ const useStyles = makeStyles((theme) => ({
},
}));
export const NotificationBar = ({ forceUncollapse }: { forceUncollapse: boolean }) => {
export const NotificationBar = () => {
const classes = useStyles();
const history = useHistory();
const { icons, notifications, removeNotification } = useNotifications();
const [uncollapsed, setUncollapsed] = useState<boolean>(false);
const {
icons,
notifications,
removeNotification,
barUncollapsed,
setBarUncollapsed,
} = useNotifications();
return (
<>
@@ -83,7 +82,7 @@ export const NotificationBar = ({ forceUncollapse }: { forceUncollapse: boolean
justify='space-between'
wrap='nowrap'
onClick={() => {
setUncollapsed(!uncollapsed);
setBarUncollapsed((curr) => !curr);
}}
>
<Grid container item wrap='nowrap'>
@@ -120,41 +119,30 @@ export const NotificationBar = ({ forceUncollapse }: { forceUncollapse: boolean
</Grid>
</Grid>
</Grid>
<Slide direction='down' in={forceUncollapse || uncollapsed}>
<Slide direction='down' in={barUncollapsed}>
<Paper square className={classes.drawer}>
<Box p={2}>
<Box py={2}>
<List>
<Divider />
{notifications.map(({ href, title, content, icon }, idx) => (
<ListItem
divider
button
onClick={() => {
if (href) {
history.push(href);
setUncollapsed(false);
{notifications.map((notification, idx) => (
<NotificationItem
key={idx}
{...notification}
onClose={(e) => {
e.stopPropagation();
notification.onClose?.(notification);
if (notifications.length === 1) {
setBarUncollapsed(false);
}
removeNotification(idx);
}}
onClickClose={() => {
setBarUncollapsed(false);
if (!notification.cantClose) {
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>
</Box>
@@ -162,7 +150,7 @@ export const NotificationBar = ({ forceUncollapse }: { forceUncollapse: boolean
<IconButton
className={classes.collapseBtn}
size='small'
onClick={() => setUncollapsed(false)}
onClick={() => setBarUncollapsed(false)}
>
<ArrowDropUpIcon />
</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 {
app: string;
id?: string;
title: string;
content?: React.ReactNode;
icon?: 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 {
key: string;
icon: JSX.Element;
@@ -16,40 +36,164 @@ interface INotificationIcon {
}
export const NotificationsContext = createContext<{
barUncollapsed: boolean;
setBarUncollapsed: (v: boolean | ((c: boolean) => boolean)) => void;
notifications: INotification[];
currentAlert: INotificationAlert;
icons: INotificationIcon[];
count: number;
removeAlerts(): void;
addOrUpdateNotification(add: INotification, update?: INotification): void;
addNotification(value: INotification): void;
updateNotification(idx: number, value: INotification): 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);
export function NotificationsProvider({ children }) {
const isPhoneOpen = useRecoilValue(phoneState.visibility);
const [barUncollapsed, setBarUncollapsed] = useState<boolean>(false);
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(
(idx: number, value: INotification) => {
setNotifications((all) => {
const updated = [...all];
updated.splice(idx, 0, value);
updated.splice(idx, 1, value);
return updated;
});
},
[]
);
const removeNotification = useCallback((idx) => {
const removeNotification = (idx) => {
setNotifications((all) => {
const updated = [...all];
const updated = all;
updated.splice(idx, 1);
return updated;
return [...updated];
});
}, []);
};
const addNotification = useCallback((value: INotification) => {
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(
() =>
notifications.reduce((icons, curr) => {
@@ -64,13 +208,26 @@ export function NotificationsProvider({ children }) {
[notifications]
);
const removeAlerts = () => {
setAlerts([]);
setCurrentAlert(null);
};
return (
<NotificationsContext.Provider
value={{
setBarUncollapsed,
barUncollapsed,
currentAlert,
notifications,
removeAlerts,
addNotification,
updateNotification,
removeNotification,
updateId,
removeId,
hasNotification,
addNotificationAlert,
addOrUpdateNotification,
icons,
count: notifications.length,
}}
+10 -13
View File
@@ -16,17 +16,16 @@ interface IOptions {
* @param options Any options to pass to the addEventListener
**/
export const useNuiEvent = (
const defaultOptions = {};
export const useNuiEvent = <S = Record<string, unknown>>(
app: string,
method: string,
handler: Function,
options: IOptions = {},
currentState?: Record<string, unknown>
currentState?: S,
options: IOptions = defaultOptions
) => {
const savedHandler: MutableRefObject<any> = useRef();
// Destructure passed options
const { capture, passive, once } = options;
// When handler value changes set mutable ref to handler val
useEffect(() => {
@@ -44,15 +43,13 @@ export const useNuiEvent = (
data: event.data,
level: 1,
});
const newData = currentState ? { ...currentState, ...data } : data
savedHandler.current(newData)
const newData = currentState ? { ...currentState, ...data } : data;
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
return () => window.removeEventListener(eventName, eventListener, opts);
}, [app, method, capture, passive, once, currentState]);
return () => window.removeEventListener(eventName, eventListener, options);
}, [app, method, currentState, options]);
};
+20 -6
View File
@@ -1,15 +1,29 @@
import { useRecoilState } from 'recoil';
import { phoneState } from './state';
import { useRecoilValue } from 'recoil';
import { IServerConfig } from '../../../common/typings/config';
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 {
visibility: boolean;
setVisibility(v: boolean): void;
config?: IServerConfig;
openPhone(): void;
closePhone(): void;
isPhoneOpen: boolean;
}
export const usePhone = (): IUsePhone => {
const [visibility, setVisibility] = useRecoilState(phoneState.visibility);
return { visibility, setVisibility, config: ServerConfig as any };
const isPhoneOpen = useRecoilValue(phoneState.visibility);
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 { 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 = () => {
const { setVisibility, visibility } = usePhone();
const { count } = useNotifications();
const [visibility, setVisibility] = useRecoilState(phoneState.visibility);
const { currentAlert } = useNotifications();
const [{ zoom }] = useSettings();
const [notifVisibility, setNotifVisibility] = useState<boolean>(false);
const isNotificationVisibleOnly = useMemo(
() => !!(!visibility && count > 0),
[visibility, count]
);
const notificationTimer = useRef<NodeJS.Timeout>();
useEffect(() => {
if (isNotificationVisibleOnly) {
setNotifVisibility(true);
clearTimeout(notificationTimer.current);
notificationTimer.current = setTimeout(() => {
setVisibility(false);
setNotifVisibility(false);
}, 5000);
if (visibility) {
setNotifVisibility(false);
}
return () => clearTimeout(notificationTimer.current);
}, [isNotificationVisibleOnly, setVisibility]);
}, [visibility]);
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(() => {
if (isNotificationVisibleOnly) {
return `calc(-60% * ${zoom})`;
if (!visibility) {
return `calc(-70% * ${zoom})`;
}
return 0;
}, [isNotificationVisibleOnly, zoom]);
const clickEventOverride = useCallback(
(e) => {
if (isNotificationVisibleOnly) {
e.preventDefault();
e.stopPropagation();
setVisibility(true);
}
},
[setVisibility, isNotificationVisibleOnly]
);
}, [visibility, zoom]);
return {
bottom,
visibility: notifVisibility || visibility,
uncollapseNotifications: isNotificationVisibleOnly,
clickEventOverride,
};
};
+39 -34
View File
@@ -13,70 +13,75 @@ interface ISoundOptions {
*
* @param { volume, interrupt, loop} Additional options
**/
const useSound = (
url: string,
{ 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 [sound, setSound] = useState<Howl | null>(null);
// Mount & Dismount handling
useEffect(() => {
isMounted.current = true;
const sound = new Howl({
soundRef.current?.unload();
setPlaying(false);
setMounted(false);
soundRef.current = new Howl({
src: url,
volume,
loop,
volume: 1,
loop: false,
});
setSound(sound);
setMounted(true);
return () => {
isMounted.current = false;
soundRef.current?.unload();
soundRef.current = undefined;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [url]);
useEffect(() => {
if (sound) {
sound.volume(volume);
if (isMounted) {
soundRef.current.volume(volume);
}
// Shouldnt need to rerun if sound changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [volume]);
}, [volume, isMounted]);
useEffect(() => {
if (isMounted) {
soundRef.current.loop(loop);
}
}, [loop, isMounted]);
const play = useCallback(() => {
if (!sound) return;
if (!soundRef.current) return;
if (interrupt) return sound.stop();
sound.play();
if (isMounted.current) {
sound.once('end', () => {
if (!sound.playing()) {
if (isMounted) {
soundRef.current.play();
soundRef.current.once('end', () => {
if (!soundRef.current.playing()) {
setPlaying(false);
}
});
}
if (isMounted.current) {
setPlaying(true);
}
}, [interrupt, sound]);
}, [isMounted]);
const stop = useCallback(() => {
if (!sound) return;
if (!soundRef.current) return;
sound.stop();
if (isMounted.current) {
if (isMounted) {
soundRef.current.stop();
setPlaying(false);
}
}, [sound]);
}, [isMounted]);
useEffect(() => {
if (interrupt && isMounted) {
stop();
}
}, [interrupt, isMounted, stop]);
return { play, playing, stop };
};
+24 -2
View File
@@ -1,8 +1,30 @@
import React from 'react';
import MuiAlert from '@material-ui/lab/Alert';
import { makeStyles, Typography } from '@material-ui/core';
export function Alert(props) {
return <MuiAlert style={{ zIndex: 10000 }} elevation={6} variant='filled' {...props} />;
const useStyles = makeStyles({
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;
+2 -2
View File
@@ -1,5 +1,5 @@
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';
const useStyles = makeStyles(() => ({
@@ -29,7 +29,7 @@ export const AppContent = ({
backdrop,
onClickBackdrop,
...props
}: AppContentTypes) => {
}: AppContentTypes & BoxProps) => {
const classes = useStyles();
return (
<Paper className={classes.wrapper} square>
+38 -26
View File
@@ -1,56 +1,68 @@
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 { 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 {
root: any;
avatar: any;
}
const useStyles = makeStyles(
(theme): IStyles => ({
const useStyles = makeStyles<Theme, { color: string; backgroundColor: string }>(
(theme) => ({
root: {
display: 'flex',
'& > *': {
margin: theme.spacing(1),
},
padding: 0,
marginTop: theme.spacing(3),
},
avatar: {
'&:hover': {
backgroundColor: ({ backgroundColor }) => fade(backgroundColor, 0.6),
},
backgroundColor: ({ backgroundColor }) => backgroundColor,
color: ({ color }) => color,
width: theme.spacing(7),
height: theme.spacing(7),
boxShadow: theme.shadows[2],
width: theme.spacing(8),
height: theme.spacing(8),
fontSize: theme.typography.h4.fontSize,
},
tooltip: {
fontSize: 12,
},
})
);
export const AppIcon = ({
id,
nameLocale,
name,
icon,
backgroundColor,
color,
notification,
}) => {
const { t } = useTranslation();
const classes = useStyles({
backgroundColor: backgroundColor || green[50],
color: color || green[400],
});
return (
<Button className={classes.root}>
<Badge
color="error"
badgeContent={notification?.badge}
invisible={!notification || notification.badge < 2}
>
<Avatar className={classes.avatar}>
{icon || name[0].toUpperCase()}
</Avatar>
</Badge>
</Button>
<Tooltip
arrow
key={id}
title={t(nameLocale)}
placement='top'
classes={{ tooltip: classes.tooltip }}
TransitionComponent={Zoom}
>
<Button className={classes.root}>
<Badge
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 { useTranslation } from 'react-i18next';
import { Grid, makeStyles, Tooltip, Zoom } from '@material-ui/core';
import { Box, Grid } from '@material-ui/core';
import { Link } from 'react-router-dom';
import { useKeyboard } from '../../os/keyboard/hooks/useKeyboard';
const useStyles = makeStyles((theme) => ({
root: {
marginTop: theme.spacing(3),
},
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
export const GridMenu = ({
items,
Component = AppIcon,
xs = undefined,
}) => {
return (
<Grid container justify='center'>
<Grid container item>
{items &&
items.length &&
items.map((item) => (
<Tooltip
arrow
key={item.id}
title={t(item.nameLocale)}
placement='top'
classes={{ tooltip: classes.tooltip }}
TransitionComponent={Zoom}
>
<Grid
key={item.id}
item
className={classes.item}
component={Link}
to={item.path}
>
<Grid container alignItems='center' direction='row'>
{items &&
items.length &&
items.map((item) => (
<Grid
item
xs={xs}
key={item.id}
alignItems='center'
justify='center'
>
<Box textAlign='center'>
<Link to={item.path}>
<Component {...item} />
</Grid>
</Tooltip>
))}
</Grid>
</Link>
</Box>
</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 { ICall } from '../../phone/src/common/typings/call';
import {phoneCallStartAnim, phoneCallEndAnim} from './functions';
import { phoneCallStartAnim, phoneCallEndAnim } from './functions';
const exp = (global as any).exports;
@@ -21,6 +21,7 @@ onNet(
app: 'CALL',
method: 'setCaller',
data: {
active: true,
transmitter: transmitter,
receiver: receiver,
isTransmitter: isTransmitter,
@@ -41,12 +42,13 @@ onNet(
events.PHONE_CALL_WAS_ACCEPTED,
(channelId: number, currentCall: ICall, isTransmitter: boolean) => {
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(
JSON.stringify({
app: 'CALL',
method: 'setCaller',
data: {
active: true,
transmitter: currentCall.transmitter,
receiver: currentCall.receiver,
isTransmitter: isTransmitter,
@@ -75,13 +77,14 @@ onNet(events.PHONE_CALL_WAS_REJECTED, () => {
receiver: null,
isTransmitter: null,
accepted: false,
active: false,
},
})
);
});
onNet(events.PHONE_CALL_SEND_HANGUP_ANIM, () => {
phoneCallEndAnim()
phoneCallEndAnim();
});
RegisterNuiCallbackType(events.PHONE_END_CALL); // Fires when ending an ACTIVE call
@@ -104,6 +107,7 @@ onNet(events.PHONE_CALL_WAS_ENDED, () => {
receiver: null,
isTransmitter: null,
accepted: false,
active: false,
},
})
);
+36 -62
View File
@@ -1,51 +1,12 @@
import config from '../utils/config';
import events from '../utils/events';
import {phoneCloseAnim, phoneOpenAnim, removePhoneProp} from './functions';
import { phoneCloseAnim, phoneOpenAnim, removePhoneProp } from './functions';
let prop = 0;
let isPhoneOpen = false;
let propCreated = false;
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');
/* * * * * * * * * * * * *
@@ -66,7 +27,6 @@ const showPhone = async (): Promise<void> => {
data: true,
})
);
sendPhoneConfig();
SetNuiFocus(true, true);
};
@@ -84,13 +44,36 @@ const hidePhone = async (): Promise<void> => {
SetNuiFocus(false, false);
};
const togglePhoneVisible = async (): Promise<void> => {
if (isPhoneOpen) {
/* * * * * * * * * * * * *
*
* Register Command and Keybinding
*
* * * * * * * * * * * * */
RegisterCommand(
'phone:close',
async () => {
await hidePhone();
} else {
},
false
);
RegisterCommand(
'phone',
async () => {
//-- Toggles Phone
await Phone();
},
false
);
RegisterCommand(
'phone:open',
async () => {
await showPhone();
}
};
},
false
);
/* * * * * * * * * * * * *
*
@@ -99,24 +82,17 @@ const togglePhoneVisible = async (): Promise<void> => {
* * * * * * * * * * * * */
async function Phone(): Promise<void> {
fetchOnInitialize()
fetchOnInitialize();
if (config.PhoneAsItem) {
// TODO: Do promise callback here
// const hasPhoneItem = await emitNetPromise('phone:hasPhoneItem')
// if (!hasPhoneItem) return
return await togglePhoneVisible();
}
await togglePhoneVisible();
}
function sendPhoneConfig() {
SendNuiMessage(
JSON.stringify({
app: 'PHONE',
method: 'phoneConfig',
data: config,
})
);
if (isPhoneOpen) {
await hidePhone();
} else {
await showPhone();
}
}
AddEventHandler('onResourceStop', function (resource: string) {
@@ -144,7 +120,6 @@ onNet('phone:sendCredentials', (number: string) => {
);
});
// DO NOT CHANGE THIS EITHER, PLEASE - CHIP
/* * * * * * * * * * * * *
@@ -157,7 +132,6 @@ function fetchOnInitialize() {
emitNet(events.CONTACTS_GET_CONTACTS);
}
RegisterNuiCallbackType(events.OPEN_APP_LISTINGS);
on(`__cfx_nui:${events.OPEN_APP_LISTINGS}`, (data: any, cb: Function) => {
emitNet(events.SELLOUT_FETCH_LISTING);
@@ -191,7 +165,7 @@ on(`__cfx_nui:${events.OPEN_APP_DAILER}`, (data: any, cb: Function) => {
RegisterNuiCallbackType('phone:close');
on(`__cfx_nui:phone:close`, async (data: any, cb: Function) => {
await Phone();
await hidePhone();
cb();
}); // 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
-- 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 ('dphone', 'Destroyed Phone', 1, 0, 1);
+1 -1
View File
@@ -18,7 +18,7 @@ interface ContactId {
}
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 contacts = <Contacts[]>results;
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.
// Example: 123-4567
}
mainLogger.verbose(`Getting random number: ${randomNumber}`);
return randomNumber;
}
async function generatePhoneNumber(identifier: string) {
const _identifier = identifier;
let phoneNumber = await usePhoneNumber(_identifier);
let id = await getIdentifierByPhoneNumber(phoneNumber);
do {
if (!phoneNumber) {
phoneNumber = await getRandomPhoneNumber();
const query = 'UPDATE users SET phone_number = ? WHERE identifier = ?';
await pool.query(query, [phoneNumber, _identifier]);
} else {
break;
}
} while (id);
if (!await usePhoneNumber(identifier)) {
let existingId;
let newNumber;
do {
newNumber = getRandomPhoneNumber();
try {
existingId = await getIdentifierByPhoneNumber(newNumber)
} catch(e) {
existingId = false
}
} while(existingId);
mainLogger.verbose(`Inserting number into Database: ${newNumber}`);
const query = 'UPDATE users SET phone_number = ? WHERE identifier = ?';
await pool.query(query, [newNumber, identifier]);
}
}
async function getCredentials(identifier: string): Promise<string> {
@@ -65,11 +66,11 @@ async function getCredentials(identifier: string): Promise<string> {
return number[0].phone_number;
}
on('playerConnecting', async () => {
onNet('esx:playerLoaded', async (playerId: number, xPlayer: any) => {
const _source = getSource()
try {
const identifier = getIdentifier(_source);
await generatePhoneNumber(identifier)
const identifier = xPlayer.identifier;
await generatePhoneNumber(identifier);
} catch(e) {
mainLogger.error(`Failed to generate a phone number, ${e.message}`, {
source: _source,
+2 -2
View File
@@ -22,8 +22,8 @@ async function getPhotosByIdentifier(identifier: string): Promise<IPhoto[]> {
async function deletePhoto(photo: IPhoto, identifier: string) {
const query =
'DELETE FROM npwd_phone_gallery WHERE id = ? AND identifier = ?';
await pool.query(query, [photo.id, identifier]);
'DELETE FROM npwd_phone_gallery WHERE image = ? AND identifier = ?';
await pool.query(query, [photo.image, identifier]);
}
onNet(events.CAMERA_UPLOAD_PHOTO, async (image: string) => {