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 SnackbarProvider from './ui/providers/SnackbarProvider';
import Phone from './Phone';
import { SoundProvider } from './os/sound/providers/SoundProvider';
export const PhoneContainer = () => {
const currentTheme = usePhoneTheme();
return (
<ThemeProvider theme={currentTheme}>
<NotificationsProvider>
<SnackbarProvider>
<Phone />
</SnackbarProvider>
</NotificationsProvider>
<SoundProvider>
<NotificationsProvider>
<SnackbarProvider>
<Phone />
</SnackbarProvider>
</NotificationsProvider>
</SoundProvider>
</ThemeProvider>
);
};
@@ -9,7 +9,7 @@ import { AppTitle } from '../../../ui/components/AppTitle';
import PlayIcon from '@material-ui/icons/PlayArrow';
import StopIcon from '@material-ui/icons/Stop';
import { Button, IconButton } from '@material-ui/core';
import useSound from '../../../os/phone/hooks/useSound';
import useSound from '../../../os/sound/hooks/useSound';
export const ExampleApp = () => {
// calling the example hook, and we assign the value to a variable
@@ -1,10 +1,5 @@
import React from 'react';
import {
ListItem,
ListItemText,
Divider,
ListItemIcon,
} from '@material-ui/core';
import { ListItem, ListItemText, ListItemIcon } from '@material-ui/core';
interface IProps {
options?: any;
@@ -19,26 +14,12 @@ export const SettingItem = ({
label,
value,
onClick,
icon
icon,
}: IProps) => {
if (!onClick)
return (
<>
<ListItem button>
<ListItemIcon>{icon}</ListItemIcon>
<ListItemText primary={label} secondary={value ? value : undefined} />
</ListItem>
<Divider />
</>
);
return (
<>
<ListItem onClick={() => onClick(options)} button>
<ListItemIcon>{icon}</ListItemIcon>
<ListItemText primary={label} secondary={value ? value : undefined} />
</ListItem>
<Divider />
</>
<ListItem divider onClick={() => onClick?.(options)} button>
<ListItemIcon>{icon}</ListItemIcon>
<ListItemText primary={label} secondary={value ? value : undefined} />
</ListItem>
);
};
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import { AppWrapper } from '../../../ui/components';
import { AppTitle } from '../../../ui/components/AppTitle';
import { AppContent } from '../../../ui/components/AppContent';
@@ -23,12 +23,20 @@ import {
VolumeUp,
} 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 { settingsState } from '../hooks/useSettings';
const SubHeaderComp = (props: { text: string }) => (
<ListSubheader component='div' disableSticky>
<ListSubheader color='primary' component='div' disableSticky>
{props.text}
</ListSubheader>
);
@@ -43,6 +51,33 @@ export const SettingsApp = () => {
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 wallpapers = config.wallpapers.map(
@@ -65,18 +100,22 @@ export const SettingsApp = () => {
handleSettingChange('zoom', val)
)
);
// Doesn't actually do anything for the time being
const ringtones = config.ringtones.map(
MapStringOptions(settings.ringtone, (val: string) =>
handleSettingChange('ringtone', val)
)
);
// * Probably gonna make this a slider component in the future
// const ringtoneVols = config.ringtoneVols.map(
// MapStringOptions(settings.ringtoneVol, (val: number) => setSettings('ringtoneVol', val))
// )
const notifications = config.notifications.map(
MapStringOptions(settings.notification, (val: string) =>
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();
return (
@@ -96,17 +135,58 @@ export const SettingsApp = () => {
onClick={openMenu}
icon={<LibraryMusic />}
/>
{
// * NOTE: This component is most likely temporary
// * Probably want to make it a slider in the future. Ignore hardcoded for the meantime
}
<ListItem divider>
<ListItemIcon>
<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
label={t('APPS_SETTINGS_OPTION_RINGTONEVOL')}
value='100%'
options={['100%', '80%', '70%']}
label={t('APPS_SETTINGS_OPTION_NOTIFICATION')}
value={settings.notification}
options={notifications}
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 disablePadding subheader={<SubHeaderComp text='Appearance' />}>
<SettingItem
@@ -138,6 +218,41 @@ export const SettingsApp = () => {
icon={<ZoomIn />}
/>
</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>
<ContextMenu />
</AppWrapper>
+6 -1
View File
@@ -22,13 +22,18 @@ export const settingsState = atom({
effects_UNSTABLE: [localStorageEffect('settings')],
});
interface IPhoneSettings {
export interface IPhoneSettings {
wallpaper: string;
frame: string;
theme: string;
zoom: number;
ringtone: string;
ringtoneVol: number;
notification: string;
notificationVol: number;
TWITTER_notification: string;
TWITTER_notificationVol: number;
TWITTER_notifyNewFeedTweet: boolean;
}
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: {
fontSize: '18px',
wordBreak: 'break-all',
},
buttonContainer: {
display: 'flex',
@@ -1,17 +1,23 @@
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { useRecoilState } from "recoil";
import { useApp } from "../../../os/apps/hooks/useApps";
import { useNotifications } from "../../../os/notifications/hooks/useNotifications";
import { twitterState } from "./state";
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router-dom';
import { useRecoilState } from 'recoil';
import { useApp } from '../../../os/apps/hooks/useApps';
import { useNotifications } from '../../../os/notifications/hooks/useNotifications';
import { twitterState } from './state';
export const useTwitterNotifications = () => {
const { t } = useTranslation();
const history = useHistory();
const { addNotificationAlert } = useNotifications();
const { icon, notificationIcon } = useApp('TWITTER');
const [unreadCount, setUnreadCount] = useRecoilState(twitterState.unreadTweetsCount);
const [unreadCount, setUnreadCount] = useRecoilState(
twitterState.unreadTweetsCount
);
const setNotification = useCallback(
({ profile_name, message }) => {
setUnreadCount((curr) => {
@@ -19,6 +25,7 @@ export const useTwitterNotifications = () => {
addNotificationAlert(
{
app: 'TWITTER',
sound: true,
title: t('APPS_TWITTER_NEW_BROADCAST', { profile_name }),
onClick: () => history.push('/twitter'),
content: message,
@@ -39,5 +46,5 @@ export const useTwitterNotifications = () => {
[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",
"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": {
"wallpaper": "projecterror.jpg",
"frame": "default.png",
"theme": "taso-dark",
"zoom": 1,
"ringtone": "pixel",
"ringtoneVol": 100
"ringtoneVol": 50,
"notification": "online",
"notificationVol": 50,
"TWITTER_notification": "online",
"TWITTER_notificationVol": 100,
"TWITTER_notifyNewFeedTweet": true
},
"debug": {
"printDebugLogs": true,
@@ -25,6 +36,7 @@
],
"zoomOptions": [1, 0.9, 0.8],
"ringtones": ["marimba", "pixel"],
"notifications": ["online", "99kr"],
"themes": {
"default-dark": {
"palette": {
@@ -44,7 +56,7 @@
"palette": {
"type": "dark",
"primary": {
"main": "#a6d4fa"
"main": "#a6d4fa"
},
"background": {
"paper": "#1c1c1c",
+3 -4
View File
@@ -103,9 +103,6 @@
"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_OPTION_WALLPAPER": "Wallpaper",
"APPS_SETTINGS_OPTION_FRAME": "Frame",
@@ -113,10 +110,12 @@
"APPS_SETTINGS_OPTION_ZOOM": "Zoom",
"APPS_SETTINGS_OPTION_RINGTONE": "Ringtone",
"APPS_SETTINGS_OPTION_RINGTONEVOL": "Ringtone Volume",
"APPS_SETTINGS_OPTION_NOTIFICATION": "Notification",
"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_UPDATE": "Update",
"GENERIC_DELETE": "Delete",
+1 -1
View File
@@ -38,7 +38,7 @@ function CallTimer({ isAccepted }) {
return () => clearInterval(timer.current)
}, [isAccepted, setDuration]);
if (!duration) return null;
if (!duration || !isAccepted) return null;
return (
<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 { useSetRecoilState } from 'recoil';
import { callerState } from './state';
import { useNotifications } from '../../notifications/hooks/useNotifications';
import { useTranslation } from 'react-i18next';
import { CallNotification } from '../components/CallNotification';
import { useCall } from './useCall';
import { CallProps } from '../../../common/typings/call';
import { useApp } from '../../apps/hooks/useApps';
import InjectDebugData from '../../debug/InjectDebugData';
import { useCallModal } from './useCallModal';
import { useHistory, useLocation } from 'react-router-dom';
const NOTIFICATION_ID = 'call:current';
import { callerState } from './state';
import { useCallNotifications } from './useCallNotifications';
import { useDuration } from './useDuration';
InjectDebugData<CallProps | boolean>([
/* {
@@ -22,7 +18,7 @@ InjectDebugData<CallProps | boolean>([
accepted: false,
isTransmitter: false,
transmitter: 'Chip',
receiver: 'Taso',
receiver: 'Taso',
active: true,
},
},
@@ -34,33 +30,19 @@ InjectDebugData<CallProps | boolean>([
]);
export const useCallService = () => {
const { t } = useTranslation();
const { modal } = useCallModal();
const history = useHistory();
const { pathname } = useLocation();
const {
addNotificationAlert,
removeId,
addNotification,
} = useNotifications();
const { call, setCall } = useCall();
const { resetDuration } = useDuration();
const { icon, notificationIcon } = useApp('DIALER');
const { setNotification } = useCallNotifications();
const setModal = useSetRecoilState(callerState.callModal);
const [modalHasBeenOpenedThisCall, setModalOpened] = useState<boolean>(false);
const callNotificationBase = {
app: 'CALL',
id: NOTIFICATION_ID,
cantClose: true,
icon,
onClick: () => history.push('/call'),
notificationIcon,
};
useEffect(() => {
setModalOpened(!!modal);
}, [modal]);
@@ -75,47 +57,10 @@ export const useCallService = () => {
}, [history, modal, pathname, modalHasBeenOpenedThisCall]);
const _setCall = (_call: CallProps) => {
resetDuration();
setCall(_call);
if (!_call || !_call.active) {
removeId(NOTIFICATION_ID);
return;
}
if (_call.accepted) {
removeId(NOTIFICATION_ID);
addNotification({
...callNotificationBase,
content: (
<CallNotification>
{t('APPS_DIALER_CURRENT_CALL_WITH', {
transmitter: _call.transmitter,
})}
</CallNotification>
),
title: t('APPS_DIALER_CURRENT_CALL_TITLE'),
});
}
if (!_call.isTransmitter && !_call.accepted) {
removeId(NOTIFICATION_ID);
addNotificationAlert(
{
...callNotificationBase,
title: t('APPS_DIALER_INCOMING_CALL_TITLE', {
transmitter: _call.transmitter,
}),
keepWhenPhoneClosed: true,
content: (
<CallNotification>
{t('APPS_DIALER_TRANSMITTER_IS_CALLING', {
transmitter: _call.transmitter,
})}
</CallNotification>
),
},
true
);
}
setNotification(_call);
};
useNuiEvent<CallProps>('CALL', 'setCaller', _setCall, call);
useNuiEvent<boolean>('CALL', 'callModal', setModal);
};
+9 -2
View File
@@ -1,7 +1,14 @@
import { useCallback } from 'react';
import { useRecoilState } from 'recoil';
import { callerState } from './state';
export const useDuration = () => {
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: {
wordBreak: 'break-all',
display: '-webkit-box',
maxWidth: '360px',
height: '60px',
@@ -5,9 +5,13 @@ import React, {
useMemo,
useRef,
useEffect,
useContext,
} from 'react';
import { useRecoilValue } from 'recoil';
import { useSettings } from '../../../apps/settings/hooks/useSettings';
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';
export interface INotification {
@@ -17,6 +21,7 @@ export interface INotification {
content?: React.ReactNode;
icon?: JSX.Element;
notificationIcon?: JSX.Element;
sound?: boolean;
cantClose?: boolean;
keepWhenPhoneClosed?: boolean;
onClose?: (notification: INotification) => void;
@@ -59,13 +64,17 @@ export const NotificationsContext = createContext<{
export function NotificationsProvider({ children }) {
const isPhoneOpen = useRecoilValue(phoneState.visibility);
const [settings] = useSettings();
const [barUncollapsed, setBarUncollapsed] = useState<boolean>(false);
const [notifications, setNotifications] = useState<INotification[]>([]);
const { mount, play } = useContext(soundContext);
const alertTimeout = useRef<NodeJS.Timeout>();
const [alerts, setAlerts] = useState<
Array<[INotification, boolean, Partial<INotification>]>
Array<[INotification, boolean, Partial<INotification>, string | undefined]>
>([]);
const [currentAlert, setCurrentAlert] = useState<INotificationAlert>();
@@ -122,7 +131,12 @@ export function NotificationsProvider({ children }) {
);
const _showAlert = useCallback(
(n: INotification, persist: boolean, update: Partial<INotification>) => {
(
n: INotification,
persist: boolean,
update: Partial<INotification>,
soundUrl: string
) => {
return new Promise<void>((res) => {
const resolve = () => {
if (persist) {
@@ -144,6 +158,10 @@ export function NotificationsProvider({ children }) {
onCloseAlert: onExit(n.onClose),
});
if (n.sound && soundUrl) {
play(soundUrl);
}
if (n.keepWhenPhoneClosed) {
return;
}
@@ -155,7 +173,7 @@ export function NotificationsProvider({ children }) {
}, DEFAULT_ALERT_HIDE_TIME + 300);
});
},
[addOrUpdateNotification]
[addOrUpdateNotification, play]
);
const addNotificationAlert = (
@@ -163,7 +181,18 @@ export function NotificationsProvider({ children }) {
persist?: boolean,
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) => {
+3
View File
@@ -1,6 +1,7 @@
import { useRecoilValue } from 'recoil';
import { IServerConfig } from '../../../common/typings/config';
import ServerConfig from '../../../config.autogen.json';
import { useCallNotifications } from '../../call/hooks/useCallNotifications';
import { useNotifications } from '../../notifications/hooks/useNotifications';
import Nui from '../../nui-events/utils/Nui';
import { phoneState } from './state';
@@ -16,9 +17,11 @@ export const usePhone = (): IUsePhone => {
const isPhoneOpen = useRecoilValue(phoneState.visibility);
const { removeAlerts } = useNotifications();
const { resetCallNotification } = useCallNotifications();
const closePhone = () => {
removeAlerts();
resetCallNotification();
Nui.send('phone:close');
};
const openPhone = () => {
@@ -38,7 +38,7 @@ export const usePhoneVisibility = () => {
const bottom = useMemo(() => {
if (!visibility) {
return `calc(-70% * ${zoom})`;
return `calc(-728px * ${zoom})`;
}
return 0;
}, [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 { 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 { green } from '@material-ui/core/colors';
import { Badge, Button, Tooltip, Zoom } from '@material-ui/core';
@@ -13,7 +13,7 @@ const useStyles = makeStyles<Theme, { color: string; backgroundColor: string }>(
},
avatar: {
'&:hover': {
backgroundColor: ({ backgroundColor }) => fade(backgroundColor, 0.6),
backgroundColor: ({ backgroundColor }) => darken(backgroundColor, 0.1),
},
backgroundColor: ({ backgroundColor }) => backgroundColor,
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 [options, setOptions] = useState(_options);
const [options, setOptions] = useState(_options || []);
const onClose = () => setOpen(false);