Feature/floating notifications calling and twitter (#112)

* Add floating notifications :O

* Add phone notifications and refactor calling ui

* This is unsafe

* Fix controls null check

* Remove go to alert

* Fix phone stuck after call

* Remove lazy mount for Phone

* Fix open/close cl_main

* Use effect for notification visibility

* Remove all alerts when phone closes

* Avoid re-render useNuiEvent

* It works now :c
This commit is contained in:
J Francisco Rader authored and GitHub committed 2021-02-23 13:19:10 -05:00
1 parent 4633146d40
commit f6d7a3dbe1
42 files changed
+869 -679

No files matched your search

@@ -0,0 +1,66 @@
import React from 'react';
import CallIcon from '@material-ui/icons/Call';
import CallEndIcon from '@material-ui/icons/CallEnd';
import { Fab } from '@material-ui/core';
import { useCall } from '../hooks/useCall';
import useStyles from './modal.styles';
import { useModal } from '../hooks/useModal';
export const CallControls = ({
size,
}: {
size?: 'small' | 'medium' | 'large';
}) => {
const classes = useStyles();
const { setModal } = useModal();
const { call, endCall, acceptCall, rejectCall } = useCall();
if (!call) {
return null;
}
const handleRejectCall = () => {
setModal(false);
rejectCall();
};
const handleEndCall = () => {
setModal(false);
endCall();
};
const { accepted, isTransmitter } = call;
if (accepted || isTransmitter) {
return (
<Fab
size={size}
onClick={handleEndCall}
style={{ backgroundColor: '#e74c3c', color: '#fff' }}
className={classes.actionButton}
>
<CallEndIcon />
</Fab>
);
}
return (
<>
<Fab
size={size}
onClick={handleRejectCall}
style={{ backgroundColor: '#e74c3c', color: '#fff' }}
className={classes.actionButton}
>
<CallEndIcon />
</Fab>
<Fab
size={size}
onClick={acceptCall}
style={{ backgroundColor: '#27ae60', color: '#fff' }}
className={classes.actionButton}
>
<CallIcon />
</Fab>
</>
);
};
@@ -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={16}>
<h1 style={{ textAlign: 'center' }}>{call?.transmitter}</h1>
<CallTimer isAccepted={call?.accepted} />
</Box>
<div className={classes.actions}>
<CallControls />
</div>
</AppContent>
</AppWrapper>
);
};
@@ -0,0 +1,23 @@
import React from 'react';
import { Box } from '@material-ui/core';
import { CallControls } from './CallControls';
interface ICallNotificationProps {
onAccept(): void;
onReject(): void;
}
export const CallNotification = ({
children,
}: {
children: React.ReactNode;
}) => {
return (
<div style={{ paddingBottom: '48px' }}>
<Box>{children}</Box>
<Box style={{ position: 'absolute', bottom: 0, right: 0 }}>
<CallControls size='small' />
</Box>
</div>
);
};
@@ -0,0 +1,60 @@
import React, { useEffect, useRef } from 'react';
import { useDuration } from '../hooks/useDuration';
const runTimer = (updatedTime, setDuration) => {
let newTime = { ...updatedTime.current };
if (newTime.m >= 60) {
newTime = { ...newTime, h: newTime.h + 1, m: 0 };
}
if (newTime.s >= 60) {
newTime = { ...newTime, m: newTime.m + 1, s: 0 };
}
if (newTime.ms >= 100) {
newTime = { ...newTime, s: newTime.s + 1, ms: 0 };
}
newTime = { ...newTime, ms: newTime.ms + 1 };
updatedTime.current = newTime;
setDuration(newTime);
}
function CallTimer({ isAccepted }) {
const { duration, setDuration } = useDuration();
const updatedTime = useRef({ ms: 0, s: 0, m: 0, h: 0 });
const timer = useRef(null)
useEffect(() => {
if (isAccepted) {
runTimer(updatedTime, setDuration)
timer.current = setInterval(() => {
runTimer(updatedTime, setDuration)
}, 10);
} else {
clearInterval(timer.current);
timer.current = null;
}
return () => clearInterval(timer.current)
}, [isAccepted, setDuration]);
if (!duration) return null;
return (
<div
style={{
textAlign: 'center',
marginTop: '2em',
fontSize: 30,
}}
>
<span>{duration.h >= 10 ? duration.h : '0' + duration.h}</span>
&nbsp;:&nbsp;
<span>{duration.m >= 10 ? duration.m : '0' + duration.m}</span>
&nbsp;:&nbsp;
<span>{duration.s >= 10 ? duration.s : '0' + duration.s}</span>&nbsp;
</div>
);
}
export default CallTimer;
@@ -0,0 +1,18 @@
import { makeStyles, Theme } from '@material-ui/core/styles';
const useStyles = makeStyles((theme: Theme) => ({
actions: {
width: '100%',
margin: 'auto',
position: 'absolute',
display: 'flex',
alignContent: 'center',
justifyContent: 'center',
bottom: '10%',
},
actionButton: {
margin: 10,
},
}));
export default useStyles;
+16
View File
@@ -0,0 +1,16 @@
import { atom } from 'recoil';
export const callerState = {
currentCall: atom({
key: 'currentCall',
default: null
}),
callModal: atom({
key: 'callingModal',
default: false
}),
callDuration: atom({
key: 'callDuration',
default: {ms: 0, s: 0, m: 0, h: 0}
})
};
+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 };
};
@@ -0,0 +1,94 @@
import React 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';
const NOTIFICATION_ID = 'call:current';
InjectDebugData<CallProps>([
{
app: 'CALL',
method: 'setCaller',
data: {
accepted: false,
isTransmitter: false,
transmitter: 'Chip',
receiver: 'Taso',
active: true,
},
},
]);
export const useCallService = () => {
const { t } = useTranslation();
const {
addNotificationAlert,
removeId,
addNotification,
} = useNotifications();
const { call, setCall } = useCall();
const { icon, notificationIcon } = useApp('DIALER');
const setModal = useSetRecoilState(callerState.callModal);
const callNotificationBase = {
app: 'CALL',
id: NOTIFICATION_ID,
cantClose: true,
icon,
notificationIcon,
};
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,
}),
content: (
<CallNotification>
{t('APPS_DIALER_TRANSMITTER_IS_CALLING', {
transmitter: _call.transmitter,
})}
</CallNotification>
),
},
true
);
}
};
useNuiEvent<CallProps>('CALL', 'setCaller', _setCall, call);
useNuiEvent<boolean>('CALL', 'callModal', setModal);
};
+7
View File
@@ -0,0 +1,7 @@
import { useRecoilState } from 'recoil';
import { callerState } from './state';
export const useDuration = () => {
const [duration, setDuration] = useRecoilState(callerState.callDuration);
return { duration, setDuration}
}
+12
View File
@@ -0,0 +1,12 @@
import { useRecoilState } from 'recoil';
import { callerState } from './state';
interface ModalProps {
modal: boolean;
setModal: (show: boolean) => void;
}
export const useModal = (): ModalProps => {
const [modal, setModal] = useRecoilState(callerState.callModal);
return { modal, setModal }
}
+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(() => {
+29 -36
View File
@@ -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({
@@ -48,6 +48,7 @@ const isKeyValid = (key) => validKeys.indexOf(key) !== -1;
export const useInitKeyboard = () => {
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 });
};
};
@@ -8,8 +8,7 @@ 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 { usePhone } from '../../phone/hooks/usePhone';
const useStyles = makeStyles((theme) => ({
root: {
@@ -19,10 +18,7 @@ const useStyles = makeStyles((theme) => ({
}));
export const Navigation = () => {
const closePhone = () => {
console.log('Phone closed');
Nui.send('phone:close');
};
const { closePhone } = usePhone();
const classes = useStyles();
const history = useHistory();
@@ -38,12 +34,12 @@ export const Navigation = () => {
/>
<BottomNavigationAction
label='Close'
value={() => closePhone()}
value={closePhone}
icon={<RadioButtonUncheckedIcon />}
/>
<BottomNavigationAction
label='Back'
value={() => history.goBack()}
value={history.goBack}
icon={<KeyboardArrowLeftIcon />}
/>
</BottomNavigation>
@@ -0,0 +1,46 @@
import React from 'react';
import { Box, makeStyles } 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: {
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,
},
},
}));
export const NotificationAlert = () => {
const classes = useStyles();
const { currentAlert } = useNotifications();
return (
<div className={classes.snackbar}>
{currentAlert ? (
<Alert
onClick={() => currentAlert.onClick?.(currentAlert)}
icon={currentAlert.icon || false}
className={classes.alert}
elevation={6}
>
<AlertTitle>{currentAlert.title}</AlertTitle>
<Box width='100%'>{currentAlert.content}</Box>
</Alert>
) : null}
</div>
);
};
@@ -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,9 +63,8 @@ const useStyles = makeStyles((theme) => ({
},
}));
export const NotificationBar = ({ forceUncollapse }: { forceUncollapse: boolean }) => {
export const NotificationBar = () => {
const classes = useStyles();
const history = useHistory();
const { icons, notifications, removeNotification } = useNotifications();
@@ -120,41 +115,29 @@ export const NotificationBar = ({ forceUncollapse }: { forceUncollapse: boolean
</Grid>
</Grid>
</Grid>
<Slide direction='down' in={forceUncollapse || uncollapsed}>
<Slide direction='down' in={uncollapsed}>
<Paper square className={classes.drawer}>
<Box p={2}>
<List>
<Divider />
{notifications.map(({ href, title, content, icon }, idx) => (
<ListItem
divider
button
onClick={() => {
if (href) {
history.push(href);
{notifications.map((notification, idx) => (
<NotificationItem
key={idx}
onClose={(e) => {
e.stopPropagation();
if (notifications.length === 1) {
setUncollapsed(false);
}
removeNotification(idx);
}}
onClickClose={() => {
setUncollapsed(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>
{...notification}
/>
))}
</List>
</Box>
@@ -0,0 +1,58 @@
import React from 'react';
import CloseIcon from '@material-ui/icons/Close';
import {
IconButton,
ListItem,
ListItemAvatar,
ListItemText,
makeStyles,
} from '@material-ui/core';
import { INotification } from '../providers/NotificationsProvider';
const useStyles = makeStyles((theme) => ({
closeNotifBtn: {
position: 'absolute',
right: '8px',
top: '8px',
},
notificationItem: {
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();
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,12 +1,22 @@
import React, { createContext, useState, useCallback, useMemo } from 'react';
import React, {
createContext,
useState,
useCallback,
useMemo,
useRef,
useEffect,
} from 'react';
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;
onClick?: (notification: INotification) => void;
}
interface INotificationIcon {
@@ -17,39 +27,143 @@ interface INotificationIcon {
export const NotificationsContext = createContext<{
notifications: INotification[];
currentAlert: INotification;
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 [notifications, setNotifications] = useState<INotification[]>([]);
const alertTimeout = useRef<NodeJS.Timeout>();
const [alerts, setAlerts] = useState<
Array<[INotification, boolean, Partial<INotification>]>
>([]);
const [currentAlert, setCurrentAlert] = useState<INotification>();
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();
};
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);
setCurrentAlert({
...n,
onClick: () => {
clearTimeout(alertTimeout.current);
n.onClick?.(n);
resolve();
},
});
});
},
[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 +178,24 @@ export function NotificationsProvider({ children }) {
[notifications]
);
const removeAlerts = () => {
setAlerts([]);
setCurrentAlert(null);
};
return (
<NotificationsContext.Provider
value={{
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]);
};
+15 -6
View File
@@ -1,15 +1,24 @@
import { useRecoilState } from 'recoil';
import { phoneState } from './state';
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';
interface IUsePhone {
visibility: boolean;
setVisibility(v: boolean): void;
config?: IServerConfig;
openPhone(): void;
closePhone(): void;
}
export const usePhone = (): IUsePhone => {
const [visibility, setVisibility] = useRecoilState(phoneState.visibility);
return { visibility, setVisibility, config: ServerConfig as any };
const { removeAlerts } = useNotifications();
const closePhone = () => {
removeAlerts();
Nui.send('phone:close');
};
const openPhone = () => {
Nui.send('phone:open');
};
return { config: ServerConfig as any, closePhone, openPhone };
};
+23 -26
View File
@@ -1,56 +1,53 @@
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 [isNotificationVisibleOnly, setNotificationVisibleOnly] = useState<
boolean
>(false);
useEffect(() => {
setNotificationVisibleOnly(!!(!visibility && currentAlert));
}, [visibility, currentAlert]);
const notificationTimer = useRef<NodeJS.Timeout>();
useEffect(() => {
if (isNotificationVisibleOnly) {
setNotifVisibility(true);
clearTimeout(notificationTimer.current);
if (notificationTimer.current) {
clearTimeout(notificationTimer.current);
notificationTimer.current = undefined;
}
notificationTimer.current = setTimeout(() => {
setVisibility(false);
setNotifVisibility(false);
}, 5000);
}, DEFAULT_ALERT_HIDE_TIME);
}
return () => clearTimeout(notificationTimer.current);
return () => {
clearTimeout(notificationTimer.current);
notificationTimer.current = undefined;
};
}, [isNotificationVisibleOnly, setVisibility]);
const bottom = useMemo(() => {
if (isNotificationVisibleOnly) {
return `calc(-60% * ${zoom})`;
return `calc(-70% * ${zoom})`;
}
return 0;
}, [isNotificationVisibleOnly, zoom]);
const clickEventOverride = useCallback(
(e) => {
if (isNotificationVisibleOnly) {
e.preventDefault();
e.stopPropagation();
setVisibility(true);
}
},
[setVisibility, isNotificationVisibleOnly]
);
return {
bottom,
visibility: notifVisibility || visibility,
uncollapseNotifications: isNotificationVisibleOnly,
clickEventOverride,
};
};