cleanup: Recoil State Type Safety + Misc Cleanup (#189)

* chore(phone/settings): Removed unused state

* cleanup(phone/photos): Added type safety to photo state

* tweak(phone/marketplace): Added type safety to marketplace state

* chore(phone/match): Removed unnecessary console.log

* tweak(phone/messages): Added type safety to messages state

Also fixed ESLint warning for exported anonymous hook in useMessages.ts

* tweak(phone/match): Added type safety to match state

* tweak(phone/dialer): Cleanup & type safety for state

Renamed some types to better represent their data

* cleanup(phone/gen): Added NUI event enums for phone events

* tweak(phone/contacts): Type safety for contacts state & variable rename

Renamed and type variable in setFilteredContacts to better represent its use

* tweak(phone/gen-state): Added type-safety to gen phone global state

* tweak(phone/settings): Type safety for settings state

* tweak(phone/photos): Tweaked type for photo referral

* fix(phone/notification-comp): Fix reference to old theme config

* chore(phone/hooks): Remove keyboard service

Removed as this was unused and ESLint was not happy with it

* chore(phone): Cleaned up eslint warnings

No more warnings hooray!

* tweak(phone): Set time in dev mode

* fix(phone): Remove useNuiService that appeared somehow

* fix(phone/gallery): Fixed missing import for gallery

* Revert removing the keyboard service as this is built upon in another PR

This reverts commit 82d12255a84e918da087d988b599af98ce1fe54d.

* fix(phone/keyboard): Add useKeyboardService hook back to Phone.tsx

* fix(phone/gallery): Fix and standardized GalleryPhoto type
This commit is contained in:
Taso authored and GitHub committed 2021-04-11 10:01:38 -04:00
1 parent 1f20b980da
commit b5fca6b35b
35 files changed
+137 -148

No files matched your search

+11 -4
View File
@@ -5,7 +5,6 @@ import { Route } from 'react-router-dom';
import { CallModal } from './os/call/components/CallModal'; import { CallModal } from './os/call/components/CallModal';
import { HomeApp } from './apps/home/components/Home'; import { HomeApp } from './apps/home/components/Home';
import { Box, Paper, Slide, Typography } from '@material-ui/core'; import { Box, Paper, Slide, Typography } from '@material-ui/core';
import { useKeyboardService } from './os/keyboard/hooks/useKeyboardService';
import { NotificationBar } from './os/notifications/components/NotificationBar'; import { NotificationBar } from './os/notifications/components/NotificationBar';
import { Navigation } from './os/navigation-bar/components/Navigation'; import { Navigation } from './os/navigation-bar/components/Navigation';
import { useSimcardService } from './os/simcard/hooks/useSimcardService'; import { useSimcardService } from './os/simcard/hooks/useSimcardService';
@@ -32,7 +31,10 @@ import WindowSnackbar from './ui/components/WindowSnackbar';
import { usePhone } from './os/phone/hooks/usePhone'; import { usePhone } from './os/phone/hooks/usePhone';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useSnackbar } from './ui/hooks/useSnackbar'; import { useSnackbar } from './ui/hooks/useSnackbar';
import { PhoneEvents } from '../../typings/phone';
import dayjs from 'dayjs';
import { isDefaultWallpaper } from './apps/settings/utils/isDefaultWallpaper'; import { isDefaultWallpaper } from './apps/settings/utils/isDefaultWallpaper';
import { useKeyboardService } from './os/keyboard/hooks/useKeyboardService';
function Phone() { function Phone() {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
@@ -150,15 +152,20 @@ function Phone() {
export default Phone; export default Phone;
InjectDebugData([ InjectDebugData<any>([
{ {
app: 'PHONE', app: 'PHONE',
method: 'setVisibility', method: PhoneEvents.SET_VISIBILITY,
data: true, data: true,
}, },
{ {
app: 'PHONE', app: 'PHONE',
method: 'setPhoneReady', method: PhoneEvents.SET_PHONE_READY,
data: true, data: true,
}, },
{
app: 'PHONE',
method: PhoneEvents.SET_TIME,
data: dayjs().format('hh:mm'),
},
]); ]);
@@ -6,9 +6,8 @@ import DeleteIcon from '@material-ui/icons/Delete';
import ShareIcon from '@material-ui/icons/Share'; import ShareIcon from '@material-ui/icons/Share';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { useQueryParams } from '../../../../common/hooks/useQueryParams'; import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { ICameraPhoto } from '../../hooks/useCamera';
import { ShareModal } from './ShareModal'; import { ShareModal } from './ShareModal';
import { PhotoEvents } from '../../../../../../typings/photo'; import { GalleryPhoto, PhotoEvents } from '../../../../../../typings/photo';
import { useNuiRequest } from 'fivem-nui-react-lib'; import { useNuiRequest } from 'fivem-nui-react-lib';
export const GalleryModal = () => { export const GalleryModal = () => {
@@ -20,8 +19,8 @@ export const GalleryModal = () => {
const [shareOpen, setShareOpen] = useState(null); const [shareOpen, setShareOpen] = useState(null);
const meta: ICameraPhoto = useMemo( const meta: GalleryPhoto = useMemo(
() => ({ id: query.id as string, image: query.image as string }), () => ({ id: parseInt(query.id), image: query.image as string }),
[query], [query],
); );
@@ -5,11 +5,11 @@ import MessageIcon from '@material-ui/icons/Message';
import { setClipboard } from '../../../../os/phone/hooks/useClipboard'; import { setClipboard } from '../../../../os/phone/hooks/useClipboard';
import useStyles from './modal.styles'; import useStyles from './modal.styles';
import { ICameraPhoto } from '../../hooks/useCamera';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { GalleryPhoto } from '../../../../../../typings/photo';
interface IShareModalProps { interface IShareModalProps {
meta: ICameraPhoto; meta: GalleryPhoto;
referal: string; referal: string;
onClose(): void; onClose(): void;
} }
+2 -1
View File
@@ -1,7 +1,8 @@
import { atom } from 'recoil'; import { atom } from 'recoil';
import { GalleryPhoto } from '../../../../../typings/photo';
export const photoState = { export const photoState = {
photos: atom({ photos: atom<GalleryPhoto[]>({
key: 'galleryPhotos', key: 'galleryPhotos',
default: [], default: [],
}), }),
+6 -11
View File
@@ -1,19 +1,14 @@
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { SetterOrUpdater, useRecoilState } from 'recoil'; import { SetterOrUpdater, useRecoilState } from 'recoil';
import { PhotoEvents } from '../../../../../typings/photo'; import { GalleryPhoto, PhotoEvents } from '../../../../../typings/photo';
import { useNuiEvent, useNuiCallback } from 'fivem-nui-react-lib/dist/index'; import { useNuiEvent, useNuiCallback } from 'fivem-nui-react-lib/';
import { useSnackbar } from '../../../ui/hooks/useSnackbar'; import { useSnackbar } from '../../../ui/hooks/useSnackbar';
import { photoState } from './state'; import { photoState } from './state';
export interface ICameraPhoto {
id: string;
image: string;
}
interface IUseCamera { interface IUseCamera {
photos: ICameraPhoto[]; photos: GalleryPhoto[];
setPhotos: SetterOrUpdater<ICameraPhoto[]>; setPhotos: SetterOrUpdater<GalleryPhoto[]>;
takePhoto: () => void; takePhoto: () => void;
isLoading: boolean; isLoading: boolean;
} }
@@ -22,7 +17,7 @@ export const useCamera = (): IUseCamera => {
const { t } = useTranslation(); const { t } = useTranslation();
const { addAlert } = useSnackbar(); const { addAlert } = useSnackbar();
const [photos, setPhotos] = useRecoilState<ICameraPhoto[] | null>(photoState.photos); const [photos, setPhotos] = useRecoilState<GalleryPhoto[]>(photoState.photos);
const [isUploading, setUploading] = useState(false); const [isUploading, setUploading] = useState(false);
@@ -43,7 +38,7 @@ export const useCamera = (): IUseCamera => {
[addAlert, t], [addAlert, t],
); );
const [_takePhoto] = useNuiCallback<void, ICameraPhoto>( const [_takePhoto] = useNuiCallback<void, GalleryPhoto>(
'CAMERA', 'CAMERA',
PhotoEvents.TAKE_PHOTO, PhotoEvents.TAKE_PHOTO,
onPhotoSuccess, onPhotoSuccess,
+4 -11
View File
@@ -1,24 +1,17 @@
import { atom } from 'recoil'; import { atom } from 'recoil';
import { Contact } from '../../../../../typings/contact';
export const contactsState = { export const contactsState = {
contacts: atom({ contacts: atom<Contact[]>({
key: 'contactsList', key: 'contactsList',
default: [], default: [],
}), }),
showModal: atom({ showModal: atom<boolean>({
key: 'showModal', key: 'showModal',
default: false, default: false,
}), }),
filterContacts: atom({ filterContacts: atom<string>({
key: 'filterContacts', key: 'filterContacts',
default: '', default: '',
}), }),
showContactsModal: atom({
key: 'showContactModal',
default: false,
}),
contactDetail: atom({
key: 'contactDetail',
default: null,
}),
}; };
@@ -3,7 +3,7 @@ import { contactsState } from './state';
interface FilterdContactsProps { interface FilterdContactsProps {
filteredContacts: string; filteredContacts: string;
setFilteredContacts: (contact: any) => void; setFilteredContacts: (searchTerm: string) => void;
} }
export const useFilteredContacts = (): FilterdContactsProps => { export const useFilteredContacts = (): FilterdContactsProps => {
@@ -8,7 +8,7 @@ import { ListItem } from '../../../../ui/components/ListItem';
import { useNuiRequest } from 'fivem-nui-react-lib'; import { useNuiRequest } from 'fivem-nui-react-lib';
import { useSimcard } from '../../../../os/simcard/hooks/useSimcard'; import { useSimcard } from '../../../../os/simcard/hooks/useSimcard';
import { useContacts } from '../../../contacts/hooks/useContacts'; import { useContacts } from '../../../contacts/hooks/useContacts';
import { CallEvents, ICall } from '../../../../../../typings/call'; import { CallEvents, CallHistoryItem } from '../../../../../../typings/call';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Box, IconButton, ListItemIcon, ListItemText } from '@material-ui/core'; import { Box, IconButton, ListItemIcon, ListItemText } from '@material-ui/core';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
@@ -56,7 +56,7 @@ export const DialerHistory = ({ calls }) => {
return ( return (
<List disablePadding> <List disablePadding>
{calls.map((call: ICall) => {calls.map((call: CallHistoryItem) =>
call.transmitter === myNumber ? ( call.transmitter === myNumber ? (
<ListItem key={call.id} divider> <ListItem key={call.id} divider>
<ListItemIcon> <ListItemIcon>
+2 -1
View File
@@ -1,7 +1,8 @@
import { atom } from 'recoil'; import { atom } from 'recoil';
import { CallHistoryItem } from '../../../../../typings/call';
export const dialState = { export const dialState = {
history: atom({ history: atom<CallHistoryItem[]>({
key: 'dialHistory', key: 'dialHistory',
default: [], default: [],
}), }),
@@ -1,7 +1,6 @@
import { useRecoilValue } from 'recoil'; import { useRecoilValue } from 'recoil';
import { ICall } from '../../../../../typings/call';
import { dialState } from './state'; import { dialState } from './state';
export const useDialHistory = () => { export const useDialHistory = () => {
return useRecoilValue<ICall[]>(dialState.history); return useRecoilValue(dialState.history);
}; };
+2 -1
View File
@@ -1,7 +1,8 @@
import { atom } from 'recoil'; import { atom } from 'recoil';
import { MarketplaceListing } from '../../../../../typings/marketplace';
export const selloutState = { export const selloutState = {
listing: atom({ listing: atom<MarketplaceListing[]>({
key: 'listing', key: 'listing',
default: [], default: [],
}), }),
@@ -15,8 +15,6 @@ const useStyles = makeStyles({
export function MatchBottomNavigation({ activePage, handleChange }) { export function MatchBottomNavigation({ activePage, handleChange }) {
const classes = useStyles(); const classes = useStyles();
console.log(activePage);
return ( return (
<BottomNavigation value={activePage} onChange={handleChange} className={classes.root}> <BottomNavigation value={activePage} onChange={handleChange} className={classes.root}>
<BottomNavigationAction component={Link} to="/match" icon={<HomeIcon />} /> <BottomNavigationAction component={Link} to="/match" icon={<HomeIcon />} />
+6 -5
View File
@@ -1,7 +1,8 @@
import { atom } from 'recoil'; import { atom } from 'recoil';
import { FormattedMatch, FormattedProfile } from '../../../../../typings/match';
export const matchState = { export const matchState = {
profiles: atom({ profiles: atom<FormattedProfile[]>({
key: 'profiles', key: 'profiles',
default: null, default: null,
}), }),
@@ -9,19 +10,19 @@ export const matchState = {
key: 'errorLoadingProfiles', key: 'errorLoadingProfiles',
default: false, default: false,
}), }),
matches: atom({ matches: atom<FormattedMatch[]>({
key: 'matches', key: 'matches',
default: null, default: null,
}), }),
errorLoadingMatches: atom({ errorLoadingMatches: atom<boolean>({
key: 'errorLoadingMatches', key: 'errorLoadingMatches',
default: false, default: false,
}), }),
myProfile: atom({ myProfile: atom<FormattedProfile | null>({
key: 'myProfile', key: 'myProfile',
default: null, default: null,
}), }),
noProfileExists: atom({ noProfileExists: atom<boolean>({
key: 'noProfileExists', key: 'noProfileExists',
default: false, default: false,
}), }),
+10 -9
View File
@@ -1,32 +1,33 @@
import { atom } from 'recoil'; import { atom } from 'recoil';
import { CreateMessageGroupResult, Message, MessageGroup } from '../../../../../typings/messages';
export const messageState = { export const messageState = {
messageGroups: atom({ messageGroups: atom<MessageGroup[]>({
key: 'messageGroups', key: 'messageGroups',
default: null, default: [],
}), }),
messages: atom({ messages: atom<Message[]>({
key: 'messages', key: 'messages',
default: null, default: null,
}), }),
activeMessageGroup: atom({ activeMessageGroup: atom<MessageGroup>({
key: 'activeMessageGroup', key: 'activeMessageGroup',
default: null, default: null,
}), }),
showNewMessageGroup: atom({ showNewMessageGroup: atom<boolean>({
key: 'showNewMessageGroup', key: 'showNewMessageGroup',
default: false, default: false,
}), }),
createMessageGroupResult: atom({ createMessageGroupResult: atom<CreateMessageGroupResult>({
key: 'createMessageGroupResult', key: 'createMessageGroupResult',
default: null, default: null,
}), }),
imageModal: atom({ imageModal: atom<boolean>({
key: 'useImageModal', key: 'useImageModal',
default: false, default: false,
}), }),
unreadMessagesCount: atom({ unreadMessagesCount: atom<number>({
key: 'unreadMessagesCount', key: 'unreadMessagesCount',
default: 0, default: 0,
}) }),
}; };
+1 -1
View File
@@ -72,6 +72,6 @@ const useMessages = (): IUseMessages => {
setActiveMessageGroup, setActiveMessageGroup,
goToConversation, goToConversation,
}; };
}; }
export default useMessages; export default useMessages;
+1 -1
View File
@@ -104,7 +104,7 @@ const localStorageEffect = (key) => ({ setSelf, onSet }) => {
}); });
}; };
export const settingsState = atom({ export const settingsState = atom<IPhoneSettings>({
key: 'settings', key: 'settings',
default: config.defaultSettings, default: config.defaultSettings,
effects_UNSTABLE: [localStorageEffect(NPWD_STORAGE_KEY)], effects_UNSTABLE: [localStorageEffect(NPWD_STORAGE_KEY)],
@@ -2,10 +2,10 @@ import React from 'react';
import { Box, makeStyles } from '@material-ui/core'; import { Box, makeStyles } from '@material-ui/core';
import { CallControls } from './CallControls'; import { CallControls } from './CallControls';
interface ICallNotificationProps { // interface ICallNotificationProps {
onAccept(): void; // onAccept(): void;
onReject(): void; // onReject(): void;
} // }
const useStyles = makeStyles((theme) => ({ const useStyles = makeStyles((theme) => ({
root: { root: {
+3 -2
View File
@@ -1,11 +1,12 @@
import { atom } from 'recoil'; import { atom } from 'recoil';
import { ActiveCall } from '../../../../../typings/call';
export const callerState = { export const callerState = {
currentCall: atom({ currentCall: atom<ActiveCall>({
key: 'currentCall', key: 'currentCall',
default: null, default: null,
}), }),
callModal: atom({ callModal: atom<boolean>({
key: 'callingModal', key: 'callingModal',
default: false, default: false,
}), }),
+2 -2
View File
@@ -1,11 +1,11 @@
import { useRecoilState } from 'recoil'; import { useRecoilState } from 'recoil';
import { CallProps } from '../../../../../typings/call'; import { ActiveCall } from '../../../../../typings/call';
import { callerState } from './state'; import { callerState } from './state';
import { CallEvents } from '../../../../../typings/call'; import { CallEvents } from '../../../../../typings/call';
import { useNuiRequest } from 'fivem-nui-react-lib'; import { useNuiRequest } from 'fivem-nui-react-lib';
interface CallHook { interface CallHook {
call: CallProps; call: ActiveCall;
setCall: (details: any) => void; setCall: (details: any) => void;
acceptCall(): void; acceptCall(): void;
rejectCall(): void; rejectCall(): void;
@@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { CallProps } from '../../../../../typings/call'; import { ActiveCall } from '../../../../../typings/call';
import { useApp } from '../../apps/hooks/useApps'; import { useApp } from '../../apps/hooks/useApps';
import { useNotifications } from '../../notifications/hooks/useNotifications'; import { useNotifications } from '../../notifications/hooks/useNotifications';
import { useRingtoneSound } from '../../sound/hooks/useRingtoneSound'; import { useRingtoneSound } from '../../sound/hooks/useRingtoneSound';
@@ -27,7 +27,7 @@ export const useCallNotifications = () => {
notificationIcon, notificationIcon,
}; };
const setNotification = (call: CallProps) => { const setNotification = (call: ActiveCall) => {
stop(); stop();
if (!call || !call.active) { if (!call || !call.active) {
removeId(NOTIFICATION_ID); removeId(NOTIFICATION_ID);
+3 -2
View File
@@ -1,7 +1,8 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useSetRecoilState } from 'recoil'; import { useSetRecoilState } from 'recoil';
import { useCall } from './useCall'; import { useCall } from './useCall';
import { CallEvents, CallProps } from '../../../../../typings/call';
import { CallEvents, ActiveCall } from '../../../../../typings/call';
// import InjectDebugData from '../../debug/InjectDebugData'; // import InjectDebugData from '../../debug/InjectDebugData';
import { useCallModal } from './useCallModal'; import { useCallModal } from './useCallModal';
import { useHistory, useLocation } from 'react-router-dom'; import { useHistory, useLocation } from 'react-router-dom';
@@ -54,7 +55,7 @@ export const useCallService = () => {
} }
}, [history, modal, pathname, modalHasBeenOpenedThisCall]); }, [history, modal, pathname, modalHasBeenOpenedThisCall]);
const _setCall = (_call: CallProps) => { const _setCall = (_call: ActiveCall) => {
setCall({ ...call, ..._call }); setCall({ ...call, ..._call });
setNotification(_call); setNotification(_call);
}; };
-12
View File
@@ -1,12 +0,0 @@
import { atom } from 'recoil';
export const phoneSettings = {
theme: atom({
key: 'settingTheme',
default: 'default-dark',
}),
zoom: atom({
key: 'settingZoom',
default: '100%',
}),
};
+6 -5
View File
@@ -1,19 +1,20 @@
import { atom } from 'recoil'; import { atom } from 'recoil';
import { IServerConfig } from '../../../../../typings/config';
export const phoneState = { export const phoneState = {
visibility: atom({ visibility: atom<boolean>({
key: 'phoneVisibility', key: 'phoneVisibility',
default: false, default: false,
}), }),
phoneConfig: atom({ phoneConfig: atom<IServerConfig>({
key: 'phoneConfig', key: 'phoneConfig',
default: undefined, default: null,
}), }),
phoneReady: atom({ phoneReady: atom<boolean>({
key: 'phoneReady', key: 'phoneReady',
default: false, default: false,
}), }),
phoneTime: atom({ phoneTime: atom<string>({
key: 'phoneTime', key: 'phoneTime',
default: null, default: null,
}), }),
+4 -4
View File
@@ -16,8 +16,8 @@ export const usePhoneService = () => {
const setPhoneConfig = useSetRecoilState(phoneState.phoneConfig); const setPhoneConfig = useSetRecoilState(phoneState.phoneConfig);
const setPhoneReady = useSetRecoilState(phoneState.phoneReady); const setPhoneReady = useSetRecoilState(phoneState.phoneReady);
const setPhoneTime = useSetRecoilState(phoneState.phoneTime); const setPhoneTime = useSetRecoilState(phoneState.phoneTime);
useNuiEvent('PHONE', 'setVisibility', setVisibility); useNuiEvent('PHONE', PhoneEvents.SET_VISIBILITY, setVisibility);
useNuiEvent('PHONE', 'setPhoneReady', setPhoneReady); useNuiEvent('PHONE', PhoneEvents.SET_PHONE_READY, setPhoneReady);
useNuiEvent('PHONE', 'phoneConfig', setPhoneConfig); useNuiEvent('PHONE', PhoneEvents.SET_CONFIG, setPhoneConfig);
useNuiEvent('PHONE', 'setTime', setPhoneTime); useNuiEvent('PHONE', PhoneEvents.SET_TIME, setPhoneTime);
}; };
@@ -3,6 +3,7 @@ import { simcardState } from './state';
import { useSimcard } from './useSimcard'; import { useSimcard } from './useSimcard';
import InjectDebugData from '../../debug/InjectDebugData'; import InjectDebugData from '../../debug/InjectDebugData';
import { useNuiEvent } from 'fivem-nui-react-lib'; import { useNuiEvent } from 'fivem-nui-react-lib';
import { PhoneEvents } from '../../../../../typings/phone';
InjectDebugData([ InjectDebugData([
{ {
@@ -14,6 +15,6 @@ InjectDebugData([
export const useSimcardService = () => { export const useSimcardService = () => {
const setNumber = useSetRecoilState(simcardState.number); const setNumber = useSetRecoilState(simcardState.number);
useNuiEvent('SIMCARD', 'setNumber', setNumber); useNuiEvent('SIMCARD', PhoneEvents.SET_NUMBER, setNumber);
return useSimcard(); return useSimcard();
}; };
+4 -7
View File
@@ -2,13 +2,11 @@ import React from 'react';
import Paper from '@material-ui/core/Paper'; import Paper from '@material-ui/core/Paper';
import Snackbar from '@material-ui/core/Snackbar'; import Snackbar from '@material-ui/core/Snackbar';
import Fade from '@material-ui/core/Fade'; import Fade from '@material-ui/core/Fade';
import { createMuiTheme, ThemeProvider } from '@material-ui/core'; import { ThemeProvider } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles'; import { makeStyles } from '@material-ui/core/styles';
import { usePhone } from '../../os/phone/hooks/usePhone'; import { usePhone } from '../../os/phone/hooks/usePhone';
import { useRecoilState } from 'recoil'; import { usePhoneTheme } from '../../os/phone/hooks/usePhoneTheme';
import { settingsState } from '../../apps/settings/hooks/useSettings';
import themeConfig from '../../config/default.json';
const useStyles = makeStyles({ const useStyles = makeStyles({
paper: { paper: {
@@ -25,15 +23,14 @@ function Notification({ children, handleClose, open }) {
const classes = useStyles(); const classes = useStyles();
const { config } = usePhone(); const { config } = usePhone();
const [settings] = useRecoilState(settingsState); const currentTheme = usePhoneTheme();
if (!config) return null; if (!config) return null;
const { horizontal, vertical } = config.notificationPosition; const { horizontal, vertical } = config.notificationPosition;
const currentTheme = () => createMuiTheme(themeConfig.themes[settings.theme.value]);
return ( return (
<ThemeProvider theme={currentTheme()}> <ThemeProvider theme={currentTheme}>
<Snackbar <Snackbar
className={classes.snackBar} className={classes.snackBar}
anchorOrigin={{ horizontal, vertical }} anchorOrigin={{ horizontal, vertical }}
+22 -19
View File
@@ -1,5 +1,5 @@
import { CallEvents } from '../../typings/call'; import { CallEvents } from '../../typings/call';
import { ICall } from '../../typings/call'; import { CallHistoryItem } from '../../typings/call';
import { phoneCallStartAnim, phoneCallEndAnim } from './functions'; import { phoneCallStartAnim, phoneCallEndAnim } from './functions';
const exp = (global as any).exports; const exp = (global as any).exports;
@@ -34,23 +34,26 @@ on(`__cfx_nui:${CallEvents.ACCEPT_CALL}`, (data: any, cb: Function) => {
cb(); cb();
}); });
onNet(CallEvents.WAS_ACCEPTED, (channelId: number, currentCall: ICall, isTransmitter: boolean) => { onNet(
exp['mumble-voip'].SetCallChannel(channelId); CallEvents.WAS_ACCEPTED,
phoneCallStartAnim(); // Trigger call animation only if the call was accepted. (channelId: number, currentCall: CallHistoryItem, isTransmitter: boolean) => {
SendNuiMessage( exp['mumble-voip'].SetCallChannel(channelId);
JSON.stringify({ phoneCallStartAnim(); // Trigger call animation only if the call was accepted.
app: 'CALL', SendNuiMessage(
method: CallEvents.SET_CALLER, JSON.stringify({
data: { app: 'CALL',
active: true, method: CallEvents.SET_CALLER,
transmitter: currentCall.transmitter, data: {
receiver: currentCall.receiver, active: true,
isTransmitter: isTransmitter, transmitter: currentCall.transmitter,
accepted: true, receiver: currentCall.receiver,
}, isTransmitter: isTransmitter,
}), accepted: true,
); },
}); }),
);
},
);
RegisterNuiCallbackType(CallEvents.REJECTED); // Fires when cancelling and rejecting a call. RegisterNuiCallbackType(CallEvents.REJECTED); // Fires when cancelling and rejecting a call.
on(`__cfx_nui:${CallEvents.REJECTED}`, (data: any, cb: Function) => { on(`__cfx_nui:${CallEvents.REJECTED}`, (data: any, cb: Function) => {
@@ -115,7 +118,7 @@ function openCallModal(show: boolean) {
); );
} }
onNet(CallEvents.SEND_HISTORY, (calls: ICall) => { onNet(CallEvents.SEND_HISTORY, (calls: CallHistoryItem[]) => {
SendNuiMessage( SendNuiMessage(
JSON.stringify({ JSON.stringify({
app: 'DIALER', app: 'DIALER',
+6 -6
View File
@@ -55,14 +55,14 @@ const showPhone = async (): Promise<void> => {
await phoneOpenAnim(); // Animation starts before the phone is open await phoneOpenAnim(); // Animation starts before the phone is open
emitNet('phone:getCredentials'); emitNet('phone:getCredentials');
SetCursorLocation(0.9, 0.922); //Experimental SetCursorLocation(0.9, 0.922); //Experimental
sendMessage('PHONE', 'setVisibility', true); sendMessage('PHONE', PhoneEvents.SET_VISIBILITY, true);
sendMessage('PHONE', 'setTime', time); sendMessage('PHONE', PhoneEvents.SET_TIME, time);
SetNuiFocus(true, true); SetNuiFocus(true, true);
}; };
const hidePhone = async (): Promise<void> => { const hidePhone = async (): Promise<void> => {
isPhoneOpen = false; isPhoneOpen = false;
sendMessage('PHONE', 'setVisibility', false); sendMessage('PHONE', PhoneEvents.SET_VISIBILITY, false);
await phoneCloseAnim(); await phoneCloseAnim();
SetNuiFocus(false, false); SetNuiFocus(false, false);
}; };
@@ -119,15 +119,15 @@ onNet(PhoneEvents.PLAYER_IS_READY, () => {
AddEventHandler('onResourceStop', function (resource: string) { AddEventHandler('onResourceStop', function (resource: string) {
if (resource === GetCurrentResourceName()) { if (resource === GetCurrentResourceName()) {
sendMessage('PHONE', 'setVisibility', false); sendMessage('PHONE', PhoneEvents.SET_VISIBILITY, false);
SetNuiFocus(false, false); SetNuiFocus(false, false);
removePhoneProp(); //Deletes the phone incase it was attached. removePhoneProp(); //Deletes the phone incase it was attached.
ClearPedTasks(PlayerPedId()); //Leave here until launch as it'll fix any stuck animations. ClearPedTasks(PlayerPedId()); //Leave here until launch as it'll fix any stuck animations.
} }
}); });
onNet('phone:sendCredentials', (number: string) => { onNet(PhoneEvents.SEND_CREDENTIALS, (number: string) => {
sendMessage('SIMCARD', 'setNumber', number); sendMessage('SIMCARD', PhoneEvents.SET_NUMBER, number);
}); });
RegisterNuiCallbackType(PhoneEvents.UI_IS_READY); RegisterNuiCallbackType(PhoneEvents.UI_IS_READY);
+3 -2
View File
@@ -1,6 +1,7 @@
import { IPhoto, PhotoEvents } from '../../typings/photo'; import { IPhoto, PhotoEvents } from '../../typings/photo';
import { Delay } from '../utils/fivem'; import { Delay } from '../utils/fivem';
import { sendMessage, sendCameraEvent } from '../utils/messages'; import { sendMessage, sendCameraEvent } from '../utils/messages';
import { PhoneEvents } from '../../typings/phone';
const SCREENSHOT_BASIC_TOKEN = GetConvar('SCREENSHOT_BASIC_TOKEN', 'none'); const SCREENSHOT_BASIC_TOKEN = GetConvar('SCREENSHOT_BASIC_TOKEN', 'none');
const exp = (global as any).exports; const exp = (global as any).exports;
@@ -9,12 +10,12 @@ let inCameraMode = false;
function closePhoneTemp() { function closePhoneTemp() {
SetNuiFocus(false, false); SetNuiFocus(false, false);
sendMessage('PHONE', 'setVisibility', false); sendMessage('PHONE', PhoneEvents.SET_VISIBILITY, false);
} }
function openPhoneTemp() { function openPhoneTemp() {
SetNuiFocus(true, true); SetNuiFocus(true, true);
sendMessage('PHONE', 'setVisibility', true); sendMessage('PHONE', PhoneEvents.SET_VISIBILITY, true);
} }
function CellFrontCamActivate(activate: boolean) { function CellFrontCamActivate(activate: boolean) {
+6 -6
View File
@@ -1,7 +1,7 @@
import { CallEvents } from '../../typings/call'; import { CallEvents } from '../../typings/call';
import { getIdentifierByPhoneNumber, getPlayer, getSource } from './functions'; import { getIdentifierByPhoneNumber, getPlayer, getSource } from './functions';
import { getPlayerFromIdentifier } from './functions'; import { getPlayerFromIdentifier } from './functions';
import { ICall } from '../../typings/call'; import { CallHistoryItem } from '../../typings/call';
import { pool } from './db'; import { pool } from './db';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
@@ -9,25 +9,25 @@ import { mainLogger } from './sv_logger';
const callLogger = mainLogger.child({ module: 'calls' }); const callLogger = mainLogger.child({ module: 'calls' });
async function saveCall(call: ICall) { async function saveCall(call: CallHistoryItem) {
const query = const query =
'INSERT INTO npwd_calls (identifier, transmitter, receiver, start) VALUES (?, ?, ?, ?)'; 'INSERT INTO npwd_calls (identifier, transmitter, receiver, start) VALUES (?, ?, ?, ?)';
await pool.query(query, [call.identifier, call.transmitter, call.receiver, call.start]); await pool.query(query, [call.identifier, call.transmitter, call.receiver, call.start]);
} }
async function updateCall(call: ICall, isAccepted: boolean, end: number) { async function updateCall(call: CallHistoryItem, isAccepted: boolean, end: number) {
const query = 'UPDATE npwd_calls SET is_accepted=?, end=? WHERE identifier = ?'; const query = 'UPDATE npwd_calls SET is_accepted=?, end=? WHERE identifier = ?';
await pool.query(query, [isAccepted, end, call.identifier]); await pool.query(query, [isAccepted, end, call.identifier]);
} }
async function fetchCalls(phoneNumber: string): Promise<ICall[]> { async function fetchCalls(phoneNumber: string): Promise<CallHistoryItem[]> {
const query = 'SELECT * FROM npwd_calls WHERE receiver = ? OR transmitter = ? ORDER BY id DESC'; const query = 'SELECT * FROM npwd_calls WHERE receiver = ? OR transmitter = ? ORDER BY id DESC';
const [result] = await pool.query(query, [phoneNumber, phoneNumber]); const [result] = await pool.query(query, [phoneNumber, phoneNumber]);
const calls = <ICall[]>result; const calls = <CallHistoryItem[]>result;
return calls; return calls;
} }
let calls: Map<string, ICall> = new Map(); let calls: Map<string, CallHistoryItem> = new Map();
onNet(CallEvents.INITIALIZE_CALL, async (phoneNumber: string) => { onNet(CallEvents.INITIALIZE_CALL, async (phoneNumber: string) => {
const _source = getSource(); const _source = getSource();
+2 -1
View File
@@ -1,6 +1,7 @@
import { pool } from './db'; import { pool } from './db';
import { getIdentifier, getSource } from './functions'; import { getIdentifier, getSource } from './functions';
import { mainLogger } from './sv_logger'; import { mainLogger } from './sv_logger';
import { PhoneEvents } from '../../typings/phone';
interface Credentials { interface Credentials {
phone_number: string; phone_number: string;
@@ -19,7 +20,7 @@ onNet('phone:getCredentials', async () => {
try { try {
const identifier = getIdentifier(_source); const identifier = getIdentifier(_source);
const number = await getCredentials(identifier); const number = await getCredentials(identifier);
emitNet('phone:sendCredentials', _source, number); emitNet(PhoneEvents.SEND_CREDENTIALS, _source, number);
} catch (e) { } catch (e) {
mainLogger.error(`Failed to get a number, ${e.message}`, { mainLogger.error(`Failed to get a number, ${e.message}`, {
source: _source, source: _source,
+5 -5
View File
@@ -1,6 +1,6 @@
import { pool } from './db'; import { pool } from './db';
import { getIdentifier, getSource } from './functions'; import { getIdentifier, getSource } from './functions';
import { IPhoto, PhotoEvents } from '../../typings/photo'; import { GalleryPhoto, PhotoEvents } from '../../typings/photo';
import { mainLogger } from './sv_logger'; import { mainLogger } from './sv_logger';
const photoLogger = mainLogger.child({ module: 'photo' }); const photoLogger = mainLogger.child({ module: 'photo' });
@@ -11,13 +11,13 @@ async function uploadPhoto(identifier: string, image: string): Promise<IPhoto> {
return { id: results.insertId, image }; return { id: results.insertId, image };
} }
async function getPhotosByIdentifier(identifier: string): Promise<IPhoto[]> { async function getPhotosByIdentifier(identifier: string): Promise<GalleryPhoto[]> {
const query = 'SELECT id, image FROM npwd_phone_gallery WHERE identifier = ? ORDER BY id DESC'; const query = 'SELECT id, image FROM npwd_phone_gallery WHERE identifier = ? ORDER BY id DESC';
const [results] = await pool.query(query, [identifier]); const [results] = await pool.query(query, [identifier]);
return <IPhoto[]>results; return <GalleryPhoto[]>results;
} }
async function deletePhoto(photo: IPhoto, identifier: string) { async function deletePhoto(photo: GalleryPhoto, identifier: string) {
const query = 'DELETE FROM npwd_phone_gallery WHERE image = ? AND identifier = ?'; const query = 'DELETE FROM npwd_phone_gallery WHERE image = ? AND identifier = ?';
await pool.query(query, [photo.image, identifier]); await pool.query(query, [photo.image, identifier]);
} }
@@ -48,7 +48,7 @@ onNet(PhotoEvents.FETCH_PHOTOS, async () => {
} }
}); });
onNet(PhotoEvents.DELETE_PHOTO, async (photo: IPhoto) => { onNet(PhotoEvents.DELETE_PHOTO, async (photo: GalleryPhoto) => {
const _source = getSource(); const _source = getSource();
try { try {
const identifier = getIdentifier(_source); const identifier = getIdentifier(_source);
+2 -9
View File
@@ -1,4 +1,4 @@
export interface CallProps { export interface ActiveCall {
active: boolean; active: boolean;
accepted: boolean; accepted: boolean;
isTransmitter: boolean; isTransmitter: boolean;
@@ -6,7 +6,7 @@ export interface CallProps {
receiver: string; receiver: string;
} }
export interface ICall { export interface CallHistoryItem {
id?: number; id?: number;
identifier: string; identifier: string;
transmitter: string; transmitter: string;
@@ -18,13 +18,6 @@ export interface ICall {
accepted: boolean; accepted: boolean;
} }
export interface ICallDuration {
ms: number;
s: number;
m: number;
h: number;
}
export enum CallEvents { export enum CallEvents {
INITIALIZE_CALL = 'npwd:beginCall', INITIALIZE_CALL = 'npwd:beginCall',
START_CALL = 'npwd:startCall', START_CALL = 'npwd:startCall',
+6
View File
@@ -12,5 +12,11 @@ export enum PhoneEvents {
OPEN_PHONE = 'npwd:open', OPEN_PHONE = 'npwd:open',
CLOSE_PHONE = 'npwd:close', CLOSE_PHONE = 'npwd:close',
SET_ALERT = 'npwd:setAlert', SET_ALERT = 'npwd:setAlert',
SET_VISIBILITY = 'npwd:setVisibility',
SET_NOTIFICATION = 'npwd:setNotification', SET_NOTIFICATION = 'npwd:setNotification',
SET_NUMBER = 'npwd:setNumber',
SET_PHONE_READY = 'npwd:phoneReady',
SET_CONFIG = 'npwd:setPhoneConfig',
SET_TIME = 'npwd:setGameTime',
SEND_CREDENTIALS = 'npwd:sendCredentials',
} }
+1 -1
View File
@@ -1,4 +1,4 @@
export interface IPhoto { export interface GalleryPhoto {
image: string; image: string;
id: number; id: number;
} }