Add calling and notification sounds (#119)

* Add calling and notification sounds

* Fix notification visibility on any resolution

* Add comments

* Log howler error src

* Revert removed files im stupid

* Make sliders on settings use changeCommitted instead of onChange

* Fix ringtone paths

* Break alert words overflow

* Fix tweet overflow pepega

* Remove unused hook

* Update volume sliders in real time

* Fix resolution notifications

* Fix initial value for vol sliders

* Fix call duration timer bugs

* Add alert when phone active and phone closes

* keep notification

* Stop ringing when accept
This commit is contained in:
J Francisco Rader authored and GitHub committed 2021-03-01 17:22:58 -05:00
1 parent 8ecb91e71f
commit 4eda44b9c2
28 files changed
+589 -142

No files matched your search

Binary file not shown.
Binary file not shown.
+8 -5
View File
@@ -4,16 +4,19 @@ import { NotificationsProvider } from './os/notifications/providers/Notification
import { usePhoneTheme } from './os/phone/hooks/usePhoneTheme'; import { usePhoneTheme } from './os/phone/hooks/usePhoneTheme';
import SnackbarProvider from './ui/providers/SnackbarProvider'; import SnackbarProvider from './ui/providers/SnackbarProvider';
import Phone from './Phone'; import Phone from './Phone';
import { SoundProvider } from './os/sound/providers/SoundProvider';
export const PhoneContainer = () => { export const PhoneContainer = () => {
const currentTheme = usePhoneTheme(); const currentTheme = usePhoneTheme();
return ( return (
<ThemeProvider theme={currentTheme}> <ThemeProvider theme={currentTheme}>
<NotificationsProvider> <SoundProvider>
<SnackbarProvider> <NotificationsProvider>
<Phone /> <SnackbarProvider>
</SnackbarProvider> <Phone />
</NotificationsProvider> </SnackbarProvider>
</NotificationsProvider>
</SoundProvider>
</ThemeProvider> </ThemeProvider>
); );
}; };
@@ -9,7 +9,7 @@ import { AppTitle } from '../../../ui/components/AppTitle';
import PlayIcon from '@material-ui/icons/PlayArrow'; import PlayIcon from '@material-ui/icons/PlayArrow';
import StopIcon from '@material-ui/icons/Stop'; import StopIcon from '@material-ui/icons/Stop';
import { Button, IconButton } from '@material-ui/core'; import { Button, IconButton } from '@material-ui/core';
import useSound from '../../../os/phone/hooks/useSound'; import useSound from '../../../os/sound/hooks/useSound';
export const ExampleApp = () => { export const ExampleApp = () => {
// calling the example hook, and we assign the value to a variable // calling the example hook, and we assign the value to a variable
@@ -1,10 +1,5 @@
import React from 'react'; import React from 'react';
import { import { ListItem, ListItemText, ListItemIcon } from '@material-ui/core';
ListItem,
ListItemText,
Divider,
ListItemIcon,
} from '@material-ui/core';
interface IProps { interface IProps {
options?: any; options?: any;
@@ -19,26 +14,12 @@ export const SettingItem = ({
label, label,
value, value,
onClick, onClick,
icon icon,
}: IProps) => { }: IProps) => {
if (!onClick)
return (
<>
<ListItem button>
<ListItemIcon>{icon}</ListItemIcon>
<ListItemText primary={label} secondary={value ? value : undefined} />
</ListItem>
<Divider />
</>
);
return ( return (
<> <ListItem divider onClick={() => onClick?.(options)} button>
<ListItem onClick={() => onClick(options)} button> <ListItemIcon>{icon}</ListItemIcon>
<ListItemIcon>{icon}</ListItemIcon> <ListItemText primary={label} secondary={value ? value : undefined} />
<ListItemText primary={label} secondary={value ? value : undefined} /> </ListItem>
</ListItem>
<Divider />
</>
); );
}; };
@@ -1,4 +1,4 @@
import React from 'react'; import React, { useEffect, useState } from 'react';
import { AppWrapper } from '../../../ui/components'; import { AppWrapper } from '../../../ui/components';
import { AppTitle } from '../../../ui/components/AppTitle'; import { AppTitle } from '../../../ui/components/AppTitle';
import { AppContent } from '../../../ui/components/AppContent'; import { AppContent } from '../../../ui/components/AppContent';
@@ -23,12 +23,20 @@ import {
VolumeUp, VolumeUp,
} from '@material-ui/icons'; } from '@material-ui/icons';
import { ListSubheader } from '@material-ui/core'; import {
Box,
ListItem,
ListItemIcon,
ListItemSecondaryAction,
ListItemText,
ListSubheader,
Slider,
} from '@material-ui/core';
import { useRecoilState } from 'recoil'; import { useRecoilState } from 'recoil';
import { settingsState } from '../hooks/useSettings'; import { settingsState } from '../hooks/useSettings';
const SubHeaderComp = (props: { text: string }) => ( const SubHeaderComp = (props: { text: string }) => (
<ListSubheader component='div' disableSticky> <ListSubheader color='primary' component='div' disableSticky>
{props.text} {props.text}
</ListSubheader> </ListSubheader>
); );
@@ -43,6 +51,33 @@ export const SettingsApp = () => {
setSettings({ ...settings, [key]: value }); setSettings({ ...settings, [key]: value });
}; };
const [sliders, setSliders] = useState([]);
useEffect(() => {
setSliders((curr) => {
if (!curr.length) {
return [
settings.ringtoneVol,
settings.notificationVol,
settings.TWITTER_notificationVol,
];
}
return curr;
});
}, [
settings.notificationVol,
settings.ringtoneVol,
settings.TWITTER_notificationVol,
]);
const handleSliderChange = (idx) => (_e: any, value: number | number[]) => {
setSliders((curr) => {
const newValues = [...curr];
newValues[idx] = value;
return newValues;
});
};
const { t } = useTranslation(); const { t } = useTranslation();
const wallpapers = config.wallpapers.map( const wallpapers = config.wallpapers.map(
@@ -65,18 +100,22 @@ export const SettingsApp = () => {
handleSettingChange('zoom', val) handleSettingChange('zoom', val)
) )
); );
// Doesn't actually do anything for the time being
const ringtones = config.ringtones.map( const ringtones = config.ringtones.map(
MapStringOptions(settings.ringtone, (val: string) => MapStringOptions(settings.ringtone, (val: string) =>
handleSettingChange('ringtone', val) handleSettingChange('ringtone', val)
) )
); );
// * Probably gonna make this a slider component in the future const notifications = config.notifications.map(
// const ringtoneVols = config.ringtoneVols.map( MapStringOptions(settings.notification, (val: string) =>
// MapStringOptions(settings.ringtoneVol, (val: number) => setSettings('ringtoneVol', val)) handleSettingChange('notification', val)
// ) )
);
// TODO: These new settings all work const twitterNotifications = config.notifications.map(
MapStringOptions(settings.notification, (val: string) =>
handleSettingChange('TWITTER_notification', val)
)
);
const [openMenu, closeMenu, ContextMenu, isMenuOpen] = useContextMenu(); const [openMenu, closeMenu, ContextMenu, isMenuOpen] = useContextMenu();
return ( return (
@@ -96,17 +135,58 @@ export const SettingsApp = () => {
onClick={openMenu} onClick={openMenu}
icon={<LibraryMusic />} icon={<LibraryMusic />}
/> />
{ <ListItem divider>
// * NOTE: This component is most likely temporary <ListItemIcon>
// * Probably want to make it a slider in the future. Ignore hardcoded for the meantime <VolumeUp />
} </ListItemIcon>
<ListItemText
primary={t('APPS_SETTINGS_OPTION_RINGTONEVOL')}
secondary={settings.ringtoneVol}
/>
<ListItemSecondaryAction>
<Box p={2} width={150}>
<Slider
value={sliders[0] || settings.ringtoneVol}
min={0}
max={100}
onChange={handleSliderChange(0)}
onChangeCommitted={() =>
handleSettingChange('ringtoneVol', sliders[0])
}
/>
</Box>
,
</ListItemSecondaryAction>
</ListItem>
<SettingItem <SettingItem
label={t('APPS_SETTINGS_OPTION_RINGTONEVOL')} label={t('APPS_SETTINGS_OPTION_NOTIFICATION')}
value='100%' value={settings.notification}
options={['100%', '80%', '70%']} options={notifications}
onClick={openMenu} onClick={openMenu}
icon={<VolumeUp />} icon={<LibraryMusic />}
/> />
<ListItem divider>
<ListItemIcon>
<VolumeUp />
</ListItemIcon>
<ListItemText
primary={t('APPS_SETTINGS_OPTION_NOTIFICATIONVOL')}
secondary={settings.notificationVol}
/>
<ListItemSecondaryAction>
<Box p={2} width={150}>
<Slider
value={sliders[1] || settings.notificationVol}
min={0}
max={100}
onChange={handleSliderChange(1)}
onChangeCommitted={() =>
handleSettingChange('notificationVol', sliders[1])
}
/>
</Box>
</ListItemSecondaryAction>
</ListItem>
</List> </List>
<List disablePadding subheader={<SubHeaderComp text='Appearance' />}> <List disablePadding subheader={<SubHeaderComp text='Appearance' />}>
<SettingItem <SettingItem
@@ -138,6 +218,41 @@ export const SettingsApp = () => {
icon={<ZoomIn />} icon={<ZoomIn />}
/> />
</List> </List>
<List
disablePadding
subheader={<SubHeaderComp text={t('APPS_TWITTER')} />}
>
<SettingItem
label={t('APPS_SETTINGS_OPTION_NOTIFICATION')}
value={settings.TWITTER_notification}
options={twitterNotifications}
onClick={openMenu}
icon={<LibraryMusic />}
/>
<ListItem divider>
<ListItemIcon>
<VolumeUp />
</ListItemIcon>
<ListItemText
primary={t('APPS_SETTINGS_OPTION_NOTIFICATIONVOL')}
secondary={settings.TWITTER_notificationVol}
/>
<ListItemSecondaryAction>
<Box p={2} width={150}>
<Slider
value={sliders[2] || settings.TWITTER_notificationVol}
min={0}
max={100}
onChange={handleSliderChange(2)}
onChangeCommitted={() =>
handleSettingChange('TWITTER_notificationVol', sliders[2])
}
/>
</Box>
</ListItemSecondaryAction>
</ListItem>
</List>
</AppContent> </AppContent>
<ContextMenu /> <ContextMenu />
</AppWrapper> </AppWrapper>
+6 -1
View File
@@ -22,13 +22,18 @@ export const settingsState = atom({
effects_UNSTABLE: [localStorageEffect('settings')], effects_UNSTABLE: [localStorageEffect('settings')],
}); });
interface IPhoneSettings { export interface IPhoneSettings {
wallpaper: string; wallpaper: string;
frame: string; frame: string;
theme: string; theme: string;
zoom: number; zoom: number;
ringtone: string; ringtone: string;
ringtoneVol: number; ringtoneVol: number;
notification: string;
notificationVol: number;
TWITTER_notification: string;
TWITTER_notificationVol: number;
TWITTER_notifyNewFeedTweet: boolean;
} }
export const useSettings = () => { export const useSettings = () => {
@@ -0,0 +1,5 @@
export const getRingtonePath = (name?: string) =>
`./media/ringtones/${name || 'pixel'}.ogg`;
export const getNotificationPath = (name?: string) =>
`./media/notifications/${name || 'online'}.ogg`;
@@ -190,5 +190,5 @@ InjectDebugData(
}, },
}, },
], ],
2000 3000
); );
@@ -48,6 +48,7 @@ const useStyles = makeStyles(() => ({
}, },
message: { message: {
fontSize: '18px', fontSize: '18px',
wordBreak: 'break-all',
}, },
buttonContainer: { buttonContainer: {
display: 'flex', display: 'flex',
@@ -1,17 +1,23 @@
import { useCallback } from "react"; import { useCallback } 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 { useRecoilState } from "recoil"; import { useRecoilState } from 'recoil';
import { useApp } from "../../../os/apps/hooks/useApps"; import { useApp } from '../../../os/apps/hooks/useApps';
import { useNotifications } from "../../../os/notifications/hooks/useNotifications"; import { useNotifications } from '../../../os/notifications/hooks/useNotifications';
import { twitterState } from "./state"; import { twitterState } from './state';
export const useTwitterNotifications = () => { export const useTwitterNotifications = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const history = useHistory(); const history = useHistory();
const { addNotificationAlert } = useNotifications(); const { addNotificationAlert } = useNotifications();
const { icon, notificationIcon } = useApp('TWITTER'); const { icon, notificationIcon } = useApp('TWITTER');
const [unreadCount, setUnreadCount] = useRecoilState(twitterState.unreadTweetsCount);
const [unreadCount, setUnreadCount] = useRecoilState(
twitterState.unreadTweetsCount
);
const setNotification = useCallback( const setNotification = useCallback(
({ profile_name, message }) => { ({ profile_name, message }) => {
setUnreadCount((curr) => { setUnreadCount((curr) => {
@@ -19,6 +25,7 @@ export const useTwitterNotifications = () => {
addNotificationAlert( addNotificationAlert(
{ {
app: 'TWITTER', app: 'TWITTER',
sound: true,
title: t('APPS_TWITTER_NEW_BROADCAST', { profile_name }), title: t('APPS_TWITTER_NEW_BROADCAST', { profile_name }),
onClick: () => history.push('/twitter'), onClick: () => history.push('/twitter'),
content: message, content: message,
@@ -39,5 +46,5 @@ export const useTwitterNotifications = () => {
[setUnreadCount, addNotificationAlert, t, icon, notificationIcon, history] [setUnreadCount, addNotificationAlert, t, icon, notificationIcon, history]
); );
return { setNotification, setUnreadCount, unreadCount } return { setNotification, setUnreadCount, unreadCount };
}; };
@@ -0,0 +1,13 @@
import { useEffect, useRef } from 'react';
export function usePreviousState(value) {
// The ref object is a generic container whose current property is mutable ...
// ... and can hold any value, similar to an instance property on a class
const ref = useRef();
// Store current value in ref
useEffect(() => {
ref.current = value;
}, [value]); // Only re-run if value changes
// Return previous value (happens before update in useEffect above)
return ref.current;
}
+15 -3
View File
@@ -1,14 +1,25 @@
{ {
"cellProvider": "AT&T", "cellProvider": "AT&T",
"language": "en", "language": "en",
"wallpapers": ["beach.jpg", "minimal.jpg", "surf.jpg", "waves.jpg", "projecterror.jpg"], "wallpapers": [
"beach.jpg",
"minimal.jpg",
"surf.jpg",
"waves.jpg",
"projecterror.jpg"
],
"defaultSettings": { "defaultSettings": {
"wallpaper": "projecterror.jpg", "wallpaper": "projecterror.jpg",
"frame": "default.png", "frame": "default.png",
"theme": "taso-dark", "theme": "taso-dark",
"zoom": 1, "zoom": 1,
"ringtone": "pixel", "ringtone": "pixel",
"ringtoneVol": 100 "ringtoneVol": 50,
"notification": "online",
"notificationVol": 50,
"TWITTER_notification": "online",
"TWITTER_notificationVol": 100,
"TWITTER_notifyNewFeedTweet": true
}, },
"debug": { "debug": {
"printDebugLogs": true, "printDebugLogs": true,
@@ -25,6 +36,7 @@
], ],
"zoomOptions": [1, 0.9, 0.8], "zoomOptions": [1, 0.9, 0.8],
"ringtones": ["marimba", "pixel"], "ringtones": ["marimba", "pixel"],
"notifications": ["online", "99kr"],
"themes": { "themes": {
"default-dark": { "default-dark": {
"palette": { "palette": {
@@ -44,7 +56,7 @@
"palette": { "palette": {
"type": "dark", "type": "dark",
"primary": { "primary": {
"main": "#a6d4fa" "main": "#a6d4fa"
}, },
"background": { "background": {
"paper": "#1c1c1c", "paper": "#1c1c1c",
+3 -4
View File
@@ -103,9 +103,6 @@
"APPS_CALCULATOR_COPIED": "Result was copied to clipboard!", "APPS_CALCULATOR_COPIED": "Result was copied to clipboard!",
"APPS_MARKETPLACE_CREATE_LISTING_SUCCESS": "Successfully created a new listing",
"APPS_MARKETPALCE_CREATE_LISTING_FAILED": "Failed to create a new listing",
"APPS_SETTINGS_PHONE_NUMBER": "Phone Number", "APPS_SETTINGS_PHONE_NUMBER": "Phone Number",
"APPS_SETTINGS_OPTION_WALLPAPER": "Wallpaper", "APPS_SETTINGS_OPTION_WALLPAPER": "Wallpaper",
"APPS_SETTINGS_OPTION_FRAME": "Frame", "APPS_SETTINGS_OPTION_FRAME": "Frame",
@@ -113,10 +110,12 @@
"APPS_SETTINGS_OPTION_ZOOM": "Zoom", "APPS_SETTINGS_OPTION_ZOOM": "Zoom",
"APPS_SETTINGS_OPTION_RINGTONE": "Ringtone", "APPS_SETTINGS_OPTION_RINGTONE": "Ringtone",
"APPS_SETTINGS_OPTION_RINGTONEVOL": "Ringtone Volume", "APPS_SETTINGS_OPTION_RINGTONEVOL": "Ringtone Volume",
"APPS_SETTINGS_OPTION_NOTIFICATION": "Notification", "APPS_SETTINGS_OPTION_NOTIFICATION": "Notification",
"APPS_SETTINGS_OPTION_NOTIFICATIONVOL": "Notification Volume", "APPS_SETTINGS_OPTION_NOTIFICATIONVOL": "Notification Volume",
"APPS_MARKETPLACE_CREATE_LISTING_SUCCESS": "Successfully created a new listing",
"APPS_MARKETPALCE_CREATE_LISTING_FAILED": "Failed to create a new listing",
"GENERIC_SAVE": "Save", "GENERIC_SAVE": "Save",
"GENERIC_UPDATE": "Update", "GENERIC_UPDATE": "Update",
"GENERIC_DELETE": "Delete", "GENERIC_DELETE": "Delete",
+1 -1
View File
@@ -38,7 +38,7 @@ function CallTimer({ isAccepted }) {
return () => clearInterval(timer.current) return () => clearInterval(timer.current)
}, [isAccepted, setDuration]); }, [isAccepted, setDuration]);
if (!duration) return null; if (!duration || !isAccepted) return null;
return ( return (
<div <div
@@ -0,0 +1,86 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router-dom';
import { CallProps } from '../../../common/typings/call';
import { useApp } from '../../apps/hooks/useApps';
import { useNotifications } from '../../notifications/hooks/useNotifications';
import { useRingtoneSound } from '../../sound/hooks/useRingtoneSound';
import { CallNotification } from '../components/CallNotification';
import { useCall } from './useCall';
const NOTIFICATION_ID = 'call:current';
export const useCallNotifications = () => {
const { t } = useTranslation();
const history = useHistory();
const { addNotificationAlert, removeId } = useNotifications();
const { play, stop, playing } = useRingtoneSound();
const { icon, notificationIcon } = useApp('DIALER');
const callNotificationBase = {
app: 'CALL',
id: NOTIFICATION_ID,
cantClose: true,
icon,
onClick: () => history.push('/call'),
notificationIcon,
};
const { call } = useCall();
const setNotification = (call: CallProps) => {
if (!call || !call.active) {
stop();
removeId(NOTIFICATION_ID);
return;
}
if (call.accepted) {
stop();
removeId(NOTIFICATION_ID);
addNotificationAlert(
{
...callNotificationBase,
keepWhenPhoneClosed: true,
content: (
<CallNotification>
{t('APPS_DIALER_CURRENT_CALL_WITH', {
transmitter: call.transmitter,
})}
</CallNotification>
),
title: t('APPS_DIALER_CURRENT_CALL_TITLE'),
},
true
);
}
if (!call.isTransmitter && !call.accepted) {
if (!playing()) {
play();
}
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
);
}
};
const resetCallNotification = () => setNotification(call);
return { setNotification, resetCallNotification };
};
+9 -64
View File
@@ -1,18 +1,14 @@
import React, { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useNuiEvent } from '../../nui-events/hooks/useNuiEvent'; import { useNuiEvent } from '../../nui-events/hooks/useNuiEvent';
import { useSetRecoilState } from 'recoil'; 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 { useCall } from './useCall';
import { CallProps } from '../../../common/typings/call'; import { CallProps } from '../../../common/typings/call';
import { useApp } from '../../apps/hooks/useApps';
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';
import { callerState } from './state';
const NOTIFICATION_ID = 'call:current'; import { useCallNotifications } from './useCallNotifications';
import { useDuration } from './useDuration';
InjectDebugData<CallProps | boolean>([ InjectDebugData<CallProps | boolean>([
/* { /* {
@@ -22,7 +18,7 @@ InjectDebugData<CallProps | boolean>([
accepted: false, accepted: false,
isTransmitter: false, isTransmitter: false,
transmitter: 'Chip', transmitter: 'Chip',
receiver: 'Taso', receiver: 'Taso',
active: true, active: true,
}, },
}, },
@@ -34,33 +30,19 @@ InjectDebugData<CallProps | boolean>([
]); ]);
export const useCallService = () => { export const useCallService = () => {
const { t } = useTranslation();
const { modal } = useCallModal(); const { modal } = useCallModal();
const history = useHistory(); const history = useHistory();
const { pathname } = useLocation(); const { pathname } = useLocation();
const {
addNotificationAlert,
removeId,
addNotification,
} = useNotifications();
const { call, setCall } = useCall(); const { call, setCall } = useCall();
const { resetDuration } = useDuration();
const { icon, notificationIcon } = useApp('DIALER'); const { setNotification } = useCallNotifications();
const setModal = useSetRecoilState(callerState.callModal); const setModal = useSetRecoilState(callerState.callModal);
const [modalHasBeenOpenedThisCall, setModalOpened] = useState<boolean>(false); const [modalHasBeenOpenedThisCall, setModalOpened] = useState<boolean>(false);
const callNotificationBase = {
app: 'CALL',
id: NOTIFICATION_ID,
cantClose: true,
icon,
onClick: () => history.push('/call'),
notificationIcon,
};
useEffect(() => { useEffect(() => {
setModalOpened(!!modal); setModalOpened(!!modal);
}, [modal]); }, [modal]);
@@ -75,47 +57,10 @@ export const useCallService = () => {
}, [history, modal, pathname, modalHasBeenOpenedThisCall]); }, [history, modal, pathname, modalHasBeenOpenedThisCall]);
const _setCall = (_call: CallProps) => { const _setCall = (_call: CallProps) => {
resetDuration();
setCall(_call); setCall(_call);
if (!_call || !_call.active) { setNotification(_call);
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<CallProps>('CALL', 'setCaller', _setCall, call);
useNuiEvent<boolean>('CALL', 'callModal', setModal); useNuiEvent<boolean>('CALL', 'callModal', setModal);
}; };
+9 -2
View File
@@ -1,7 +1,14 @@
import { useCallback } from 'react';
import { useRecoilState } from 'recoil'; import { useRecoilState } from 'recoil';
import { callerState } from './state'; import { callerState } from './state';
export const useDuration = () => { export const useDuration = () => {
const [duration, setDuration] = useRecoilState(callerState.callDuration); const [duration, setDuration] = useRecoilState(callerState.callDuration);
return { duration, setDuration}
} const resetDuration = useCallback(
() => setDuration({ ms: 0, s: 0, m: 0, h: 0 }),
[setDuration]
);
return { duration, setDuration, resetDuration };
};
@@ -29,6 +29,7 @@ const useStyles = makeStyles((theme) => ({
}, },
}, },
alertContent: { alertContent: {
wordBreak: 'break-all',
display: '-webkit-box', display: '-webkit-box',
maxWidth: '360px', maxWidth: '360px',
height: '60px', height: '60px',
@@ -5,9 +5,13 @@ import React, {
useMemo, useMemo,
useRef, useRef,
useEffect, useEffect,
useContext,
} from 'react'; } from 'react';
import { useRecoilValue } from 'recoil'; import { useRecoilValue } from 'recoil';
import { useSettings } from '../../../apps/settings/hooks/useSettings';
import { phoneState } from '../../phone/hooks/state'; import { phoneState } from '../../phone/hooks/state';
import { soundContext } from '../../sound/providers/SoundProvider';
import { getSoundSettings } from '../../sound/utils/getSoundSettings';
import { DEFAULT_ALERT_HIDE_TIME } from '../notifications.constants'; import { DEFAULT_ALERT_HIDE_TIME } from '../notifications.constants';
export interface INotification { export interface INotification {
@@ -17,6 +21,7 @@ export interface INotification {
content?: React.ReactNode; content?: React.ReactNode;
icon?: JSX.Element; icon?: JSX.Element;
notificationIcon?: JSX.Element; notificationIcon?: JSX.Element;
sound?: boolean;
cantClose?: boolean; cantClose?: boolean;
keepWhenPhoneClosed?: boolean; keepWhenPhoneClosed?: boolean;
onClose?: (notification: INotification) => void; onClose?: (notification: INotification) => void;
@@ -59,13 +64,17 @@ export const NotificationsContext = createContext<{
export function NotificationsProvider({ children }) { export function NotificationsProvider({ children }) {
const isPhoneOpen = useRecoilValue(phoneState.visibility); const isPhoneOpen = useRecoilValue(phoneState.visibility);
const [settings] = useSettings();
const [barUncollapsed, setBarUncollapsed] = useState<boolean>(false); const [barUncollapsed, setBarUncollapsed] = useState<boolean>(false);
const [notifications, setNotifications] = useState<INotification[]>([]); const [notifications, setNotifications] = useState<INotification[]>([]);
const { mount, play } = useContext(soundContext);
const alertTimeout = useRef<NodeJS.Timeout>(); const alertTimeout = useRef<NodeJS.Timeout>();
const [alerts, setAlerts] = useState< const [alerts, setAlerts] = useState<
Array<[INotification, boolean, Partial<INotification>]> Array<[INotification, boolean, Partial<INotification>, string | undefined]>
>([]); >([]);
const [currentAlert, setCurrentAlert] = useState<INotificationAlert>(); const [currentAlert, setCurrentAlert] = useState<INotificationAlert>();
@@ -122,7 +131,12 @@ export function NotificationsProvider({ children }) {
); );
const _showAlert = useCallback( const _showAlert = useCallback(
(n: INotification, persist: boolean, update: Partial<INotification>) => { (
n: INotification,
persist: boolean,
update: Partial<INotification>,
soundUrl: string
) => {
return new Promise<void>((res) => { return new Promise<void>((res) => {
const resolve = () => { const resolve = () => {
if (persist) { if (persist) {
@@ -144,6 +158,10 @@ export function NotificationsProvider({ children }) {
onCloseAlert: onExit(n.onClose), onCloseAlert: onExit(n.onClose),
}); });
if (n.sound && soundUrl) {
play(soundUrl);
}
if (n.keepWhenPhoneClosed) { if (n.keepWhenPhoneClosed) {
return; return;
} }
@@ -155,7 +173,7 @@ export function NotificationsProvider({ children }) {
}, DEFAULT_ALERT_HIDE_TIME + 300); }, DEFAULT_ALERT_HIDE_TIME + 300);
}); });
}, },
[addOrUpdateNotification] [addOrUpdateNotification, play]
); );
const addNotificationAlert = ( const addNotificationAlert = (
@@ -163,7 +181,18 @@ export function NotificationsProvider({ children }) {
persist?: boolean, persist?: boolean,
update?: Partial<INotification> update?: Partial<INotification>
) => { ) => {
setAlerts((curr) => [...curr, [n, persist, update]]); if (n.sound) {
const { sound, volume } = getSoundSettings(
'notification',
settings,
n.app
);
mount(sound, volume, false).then(({ url }) =>
setAlerts((curr) => [...curr, [n, persist, update, url]])
);
return;
}
setAlerts((curr) => [...curr, [n, persist, update, undefined]]);
}; };
const removeId = (id: string) => { const removeId = (id: string) => {
+3
View File
@@ -1,6 +1,7 @@
import { useRecoilValue } from 'recoil'; import { useRecoilValue } from 'recoil';
import { IServerConfig } from '../../../common/typings/config'; import { IServerConfig } from '../../../common/typings/config';
import ServerConfig from '../../../config.autogen.json'; import ServerConfig from '../../../config.autogen.json';
import { useCallNotifications } from '../../call/hooks/useCallNotifications';
import { useNotifications } from '../../notifications/hooks/useNotifications'; import { useNotifications } from '../../notifications/hooks/useNotifications';
import Nui from '../../nui-events/utils/Nui'; import Nui from '../../nui-events/utils/Nui';
import { phoneState } from './state'; import { phoneState } from './state';
@@ -16,9 +17,11 @@ export const usePhone = (): IUsePhone => {
const isPhoneOpen = useRecoilValue(phoneState.visibility); const isPhoneOpen = useRecoilValue(phoneState.visibility);
const { removeAlerts } = useNotifications(); const { removeAlerts } = useNotifications();
const { resetCallNotification } = useCallNotifications();
const closePhone = () => { const closePhone = () => {
removeAlerts(); removeAlerts();
resetCallNotification();
Nui.send('phone:close'); Nui.send('phone:close');
}; };
const openPhone = () => { const openPhone = () => {
@@ -38,7 +38,7 @@ export const usePhoneVisibility = () => {
const bottom = useMemo(() => { const bottom = useMemo(() => {
if (!visibility) { if (!visibility) {
return `calc(-70% * ${zoom})`; return `calc(-728px * ${zoom})`;
} }
return 0; return 0;
}, [visibility, zoom]); }, [visibility, zoom]);
@@ -0,0 +1,47 @@
import { useCallback, useContext, useEffect, useMemo } from 'react';
import { useSettings } from '../../../apps/settings/hooks/useSettings';
import { soundContext } from '../providers/SoundProvider';
import { getSoundSettings } from '../utils/getSoundSettings';
export const useRingtoneSound = () => {
const [settings] = useSettings();
const context = useContext(soundContext);
if (!context) {
throw new Error('useRingtoneSound must be wrapped in SoundProvider');
}
const options = useMemo(() => getSoundSettings('ringtone', settings), [
settings,
]);
useEffect(() => {
if (!context.isMounted(options.sound)) {
context.mount(options.sound, options.volume, true);
return;
}
context.volume(options.sound, options.volume);
}, [context, options.sound, options.volume]);
const play = useCallback(() => {
context.play(options.sound, options.volume, true);
}, [context, options.sound, options.volume]);
const stop = useCallback(() => {
context.stop(options.sound);
}, [context, options.sound]);
const playing = useCallback(() => {
return context.playing(options.sound);
}, [context, options.sound]);
return useMemo(
() => ({
play,
stop,
playing,
}),
[play, playing, stop]
);
};
File renamed without changes.
@@ -0,0 +1,154 @@
import { Howl } from 'howler';
import React, { createContext, useCallback, useEffect, useRef } from 'react';
interface IMountResponse {
howl: Howl;
url: string;
}
interface ISoundContext {
mount(
url: string,
volume?: number,
loop?: boolean,
autoplay?: boolean
): Promise<IMountResponse>;
play(url?: string, volume?: number, loop?: boolean): void;
stop(url: string): void;
remove(url: string): boolean;
volume(url: string, volume?: number): number;
playing(url: string): boolean;
isMounted(url: string): boolean;
}
export const soundContext = createContext<ISoundContext>(null);
export const SoundProvider = ({ children }: { children: React.ReactNode }) => {
const soundRefs = useRef<Map<string, { howl: Howl; volume: number }>>();
useEffect(() => {
soundRefs.current = new Map();
}, []);
const mount = (
url: string,
volume: number = 1,
loop: boolean = false,
autoplay: boolean = false
) => {
return new Promise<IMountResponse>((res) => {
if (!soundRefs.current) {
soundRefs.current = new Map();
}
const find = soundRefs.current.get(url);
if (find) {
find.howl.volume(volume);
find.howl.loop(loop);
if (autoplay) {
find.howl.play();
}
return res({ howl: find.howl, url });
}
const instance = new Howl({
src: url,
loop,
volume,
autoplay,
});
soundRefs.current.set(url, { howl: instance, volume });
instance.once('load', () => {
console.log('ready', instance);
res({ howl: instance, url });
});
const onError = (_id, e) => {
res(null);
console.error('Howler Error \n', e, '\nid: ', _id, '\nsrc: ', url);
};
instance.once('loaderror', onError);
instance.once('playerror', onError);
});
};
const play = useCallback((url: string, volume: number, loop: boolean) => {
const sound = soundRefs.current.get(url);
let fadedSounds = [];
if (sound) {
soundRefs.current.forEach((ref, key) => {
const isCurrent = key === url;
const isPlaying = ref.howl.playing();
const isLoop = ref.howl.loop();
if (isCurrent || !isLoop || !isPlaying) {
return;
}
fadedSounds.push(ref);
const currVol = ref.howl.volume();
ref.howl.fade(currVol, currVol * 0.3, 50);
});
if (volume !== undefined) {
sound.howl.volume(volume);
}
if (loop !== undefined) {
sound.howl.loop(loop);
}
sound.howl.play();
sound.howl.once('end', () => {
fadedSounds.forEach((s) => {
s.howl.fade(s.howl.volume(), s.volume, 50);
});
fadedSounds = undefined;
});
return;
}
mount(url, volume, loop, true);
}, []);
const volume = (url: string, volume: number = undefined): number => {
const sound = soundRefs.current.get(url);
return sound?.howl.volume(volume) as number;
};
const stop = (url: string) => {
const sound = soundRefs.current.get(url);
sound?.howl.stop();
};
const remove = (url: string): boolean => {
const sound = soundRefs.current.get(url);
if (sound) {
sound.howl.stop();
sound.howl.unload();
soundRefs.current.delete(url);
return true;
}
return false;
};
const isMounted = (url: string): boolean => {
if (!soundRefs.current) {
return false;
}
return !!soundRefs.current.get(url);
};
const playing = (url: string) => {
const sound = soundRefs.current.get(url);
return sound?.howl.playing() || false;
};
return (
<soundContext.Provider
value={{ mount, play, stop, playing, remove, volume, isMounted }}
>
{children}
</soundContext.Provider>
);
};
@@ -0,0 +1,34 @@
import { IPhoneSettings } from '../../../apps/settings/hooks/useSettings';
import {
getNotificationPath,
getRingtonePath,
} from '../../../apps/settings/utils/getRingtonePath';
const getPath = {
ringtone: getRingtonePath,
notification: getNotificationPath,
};
/**
* Gets the configuration for SoundProvider based on settings and apps
*/
export const getSoundSettings = (
type: 'ringtone' | 'notification',
settings: IPhoneSettings,
app?: string
) => {
try {
return app
? {
sound: getPath[type](settings[`${app}_${type}`]),
volume: settings[`${app}_${type}Vol`] / 100,
}
: {
sound: getPath[type](settings[type]),
volume: settings[`${type}Vol`] / 100,
};
} catch (e) {
console.error('getSoundSettings.ts error', e, 'Using default sounds');
return { sound: getPath[type](), volume: 1 };
}
};
+2 -2
View File
@@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { fade, makeStyles, Theme } from '@material-ui/core/styles'; import { darken, makeStyles, Theme } from '@material-ui/core/styles';
import Avatar from '@material-ui/core/Avatar'; import Avatar from '@material-ui/core/Avatar';
import { green } from '@material-ui/core/colors'; import { green } from '@material-ui/core/colors';
import { Badge, Button, Tooltip, Zoom } from '@material-ui/core'; import { Badge, Button, Tooltip, Zoom } from '@material-ui/core';
@@ -13,7 +13,7 @@ const useStyles = makeStyles<Theme, { color: string; backgroundColor: string }>(
}, },
avatar: { avatar: {
'&:hover': { '&:hover': {
backgroundColor: ({ backgroundColor }) => fade(backgroundColor, 0.6), backgroundColor: ({ backgroundColor }) => darken(backgroundColor, 0.1),
}, },
backgroundColor: ({ backgroundColor }) => backgroundColor, backgroundColor: ({ backgroundColor }) => backgroundColor,
color: ({ color }) => color, color: ({ color }) => color,
+2 -2
View File
@@ -12,9 +12,9 @@ export const MapStringOptions = (current, onClick) => (string) => {
}; };
}; };
export const useContextMenu = (_options = []): UseContextMenu => { export const useContextMenu = (_options?): UseContextMenu => {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [options, setOptions] = useState(_options); const [options, setOptions] = useState(_options || []);
const onClose = () => setOpen(false); const onClose = () => setOpen(false);