120 in printWidth since rocky got md

This commit is contained in:
Christopher committed 2021-03-02 20:56:15 +01:00
1 parent f552c1212c
commit d27aeb3b0e
90 files changed
+398 -1146

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"printWidth": 90, "printWidth": 120,
"singleQuote": true, "singleQuote": true,
"semi": true, "semi": true,
"bracketSpacing": true, "bracketSpacing": true,
+1 -4
View File
@@ -8,8 +8,5 @@
], ],
"@babel/preset-react" "@babel/preset-react"
], ],
"plugins": [ "plugins": ["@babel/plugin-proposal-class-properties", "@babel/plugin-syntax-dynamic-import"]
"@babel/plugin-proposal-class-properties",
"@babel/plugin-syntax-dynamic-import"
]
} }
+2 -8
View File
@@ -2,14 +2,8 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<link <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
rel="stylesheet" <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Project Error - New Phone Who Dis</title> <title>Project Error - New Phone Who Dis</title>
</head> </head>
@@ -19,9 +19,7 @@ export const AccountTransactions = (): any => {
<div id="account-section"> <div id="account-section">
<div className={classes.header}> <div className={classes.header}>
<h2 className={classes.title}>{t('APPS_BANK_ACCOUNT_TRANSACTIONS')}</h2> <h2 className={classes.title}>{t('APPS_BANK_ACCOUNT_TRANSACTIONS')}</h2>
<Button className={classes.seeAll}> <Button className={classes.seeAll}>{t('APPS_BANK_ACCOUNT_SEE_TRANSACTION')}</Button>
{t('APPS_BANK_ACCOUNT_SEE_TRANSACTION')}
</Button>
</div> </div>
<div className={classes.transcationDiv}> <div className={classes.transcationDiv}>
@@ -25,11 +25,7 @@ export const BankAccount = () => {
<div> <div>
<h1 className={classes.title}>{t('APPS_BANK_ACCOUNT_TITLE')}</h1> <h1 className={classes.title}>{t('APPS_BANK_ACCOUNT_TITLE')}</h1>
</div> </div>
<BankCard <BankCard name={credentials.name} account="Checking" balance={credentials.balance} />
name={credentials.name}
account="Checking"
balance={credentials.balance}
/>
<AccountTransactions /> <AccountTransactions />
</div> </div>
); );
@@ -24,8 +24,7 @@ export const BankHome = () => {
return ( return (
<div className={classes.root}> <div className={classes.root}>
<Typography className={classes.headTitle}> <Typography className={classes.headTitle}>
<span style={{ fontWeight: 'bold' }}>{t('APPS_BANK_HOME_TITLE')}</span>,{' '} <span style={{ fontWeight: 'bold' }}>{t('APPS_BANK_HOME_TITLE')}</span>, {credentials.name}
{credentials.name}
</Typography> </Typography>
<div className={classes.accounts}> <div className={classes.accounts}>
<h2 className={classes.accountsType}>Checking:</h2> <h2 className={classes.accountsType}>Checking:</h2>
@@ -30,21 +30,9 @@ export const NavigationBar = () => {
showLabels showLabels
className={classes.root} className={classes.root}
> >
<BottomNavigationAction <BottomNavigationAction component={Link} icon={<FontAwesomeIcon icon={faHome} />} to="/bank" />
component={Link} <BottomNavigationAction component={Link} icon={<FontAwesomeIcon icon={faMoneyCheck} />} to="/bank/account" />
icon={<FontAwesomeIcon icon={faHome} />} <BottomNavigationAction component={Link} icon={<FontAwesomeIcon icon={faList} />} to="/bank/transactions" />
to="/bank"
/>
<BottomNavigationAction
component={Link}
icon={<FontAwesomeIcon icon={faMoneyCheck} />}
to="/bank/account"
/>
<BottomNavigationAction
component={Link}
icon={<FontAwesomeIcon icon={faList} />}
to="/bank/transactions"
/>
</BottomNavigation> </BottomNavigation>
); );
}; };
@@ -33,22 +33,20 @@ export const TransactionList = () => {
</div> </div>
<div className={classes.transcationDiv}> <div className={classes.transcationDiv}>
{transactionList {transactionList.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((transaction: any) => (
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) <div className={classes.transactions}>
.map((transaction: any) => ( <div>
<div className={classes.transactions}> <h1 className={classes.tranSource}>{transaction.source}</h1>
<div> <p className={classes.tranType}>{transaction.type}</p>
<h1 className={classes.tranSource}>{transaction.source}</h1>
<p className={classes.tranType}>{transaction.type}</p>
</div>
<div>
<p className={TransactionTypes[transaction.type]}>
{transaction.type === 'Withdraw' ? '-' : '+'}
{transaction.amount}
</p>
</div>
</div> </div>
))} <div>
<p className={TransactionTypes[transaction.type]}>
{transaction.type === 'Withdraw' ? '-' : '+'}
{transaction.amount}
</p>
</div>
</div>
))}
<TablePagination <TablePagination
rowsPerPageOptions={[3, 5]} rowsPerPageOptions={[3, 5]}
className={classes.pagination} className={classes.pagination}
@@ -28,18 +28,9 @@ export const GalleryGrid = () => {
if (!photos) if (!photos)
return ( return (
<Box <Box display="flex" flexWrap="wrap" alignContent="flex-start" className={classes.root}>
display="flex"
flexWrap="wrap"
alignContent="flex-start"
className={classes.root}
>
<Box> <Box>
<Button <Button onClick={handleCamera} style={{ borderRadius: 0 }} className={classes.photo}>
onClick={handleCamera}
style={{ borderRadius: 0 }}
className={classes.photo}
>
<AddIcon fontSize="large" /> <AddIcon fontSize="large" />
</Button> </Button>
</Box> </Box>
@@ -48,27 +39,15 @@ export const GalleryGrid = () => {
return ( return (
<div> <div>
<Box <Box display="flex" flexWrap="wrap" alignContent="flex-start" className={classes.root}>
display="flex"
flexWrap="wrap"
alignContent="flex-start"
className={classes.root}
>
<Box> <Box>
<Button <Button onClick={handleCamera} style={{ borderRadius: 0 }} className={classes.photo}>
onClick={handleCamera}
style={{ borderRadius: 0 }}
className={classes.photo}
>
<AddIcon fontSize="large" /> <AddIcon fontSize="large" />
</Button> </Button>
</Box> </Box>
{photos.map((photo) => ( {photos.map((photo) => (
<Box key={photo.id} onClick={() => handlePhotoOpen(photo)}> <Box key={photo.id} onClick={() => handlePhotoOpen(photo)}>
<div <div style={{ backgroundImage: `url(${photo.image})` }} className={classes.photo} />
style={{ backgroundImage: `url(${photo.image})` }}
className={classes.photo}
/>
</Box> </Box>
))} ))}
</Box> </Box>
@@ -18,10 +18,7 @@ export const GalleryModal = () => {
const [shareOpen, setShareOpen] = useState(null); const [shareOpen, setShareOpen] = useState(null);
const meta: ICameraPhoto = useMemo( const meta: ICameraPhoto = useMemo(() => ({ id: query.id as string, image: query.image as string }), [query]);
() => ({ id: query.id as string, image: query.image as string }),
[query],
);
const _handleClose = () => { const _handleClose = () => {
history.push(referal); history.push(referal);
@@ -48,10 +45,7 @@ export const GalleryModal = () => {
<Button onClick={_handleClose}> <Button onClick={_handleClose}>
<ArrowBackIcon /> <ArrowBackIcon />
</Button> </Button>
<div <div className={classes.image} style={{ backgroundImage: `url(${meta.image})` }} />
className={classes.image}
style={{ backgroundImage: `url(${meta.image})` }}
/>
<div className={classes.actionDiv}> <div className={classes.actionDiv}>
<Button onClick={handleDeletePhoto}> <Button onClick={handleDeletePhoto}>
<DeleteIcon fontSize="large" /> <DeleteIcon fontSize="large" />
@@ -28,9 +28,7 @@ export const ShareModal = ({ meta, onClose, referal }: IShareModalProps) => {
<div className={classes.shareModal}> <div className={classes.shareModal}>
<div className={classes.innerShareModal}> <div className={classes.innerShareModal}>
<> <>
<h4 style={{ textAlign: 'center', marginTop: 20 }}> <h4 style={{ textAlign: 'center', marginTop: 20 }}>Where do you want to share the photo?</h4>
Where do you want to share the photo?
</h4>
<Button>{<MessageIcon />} Message</Button> <Button>{<MessageIcon />} Message</Button>
<h4>Or just copy the image here:</h4> <h4>Or just copy the image here:</h4>
<Button onClick={handleCopyImage} variant="contained"> <Button onClick={handleCopyImage} variant="contained">
@@ -1,12 +1,6 @@
import React from 'react'; import React from 'react';
import ListItemText from '@material-ui/core/ListItemText'; import ListItemText from '@material-ui/core/ListItemText';
import { import { Button, ListItemAvatar, Avatar as MuiAvatar, List, ListItem } from '@material-ui/core';
Button,
ListItemAvatar,
Avatar as MuiAvatar,
List,
ListItem,
} from '@material-ui/core';
import { useFilteredContacts } from '../../hooks/useFilteredContacts'; import { useFilteredContacts } from '../../hooks/useFilteredContacts';
import PhoneIcon from '@material-ui/icons/Phone'; import PhoneIcon from '@material-ui/icons/Phone';
import ChatIcon from '@material-ui/icons/Chat'; import ChatIcon from '@material-ui/icons/Chat';
@@ -54,10 +48,7 @@ export const ContactList = () => {
<SearchContacts /> <SearchContacts />
<List> <List>
{contacts {contacts
.filter( .filter((contact) => contact.display.match(filteredRegEx) || contact.number.match(filteredRegEx))
(contact) =>
contact.display.match(filteredRegEx) || contact.number.match(filteredRegEx),
)
.map((contact) => ( .map((contact) => (
<ListItem key={contact.id} divider> <ListItem key={contact.id} divider>
<ListItemAvatar> <ListItemAvatar>
@@ -25,11 +25,7 @@ export const ContactPage = () => {
return ( return (
<> <>
<ContactList /> <ContactList />
<Fab <Fab color="primary" onClick={() => history.push('/contacts/-1')} className={classes.absolute}>
color="primary"
onClick={() => history.push('/contacts/-1')}
className={classes.absolute}
>
<PersonAddIcon /> <PersonAddIcon />
</Fab> </Fab>
</> </>
@@ -7,8 +7,6 @@ interface FilterdContactsProps {
} }
export const useFilteredContacts = (): FilterdContactsProps => { export const useFilteredContacts = (): FilterdContactsProps => {
const [filteredContacts, setFilteredContacts] = useRecoilState( const [filteredContacts, setFilteredContacts] = useRecoilState(contactsState.filterContacts);
contactsState.filterContacts,
);
return { filteredContacts, setFilteredContacts }; return { filteredContacts, setFilteredContacts };
}; };
@@ -44,11 +44,7 @@ export const DialerInput = () => {
return ( return (
<Box component={Paper} className={classes.root}> <Box component={Paper} className={classes.root}>
<InputBase <InputBase placeholder="Enter a number" className={classes.input} value={inputVal} />
placeholder="Enter a number"
className={classes.input}
value={inputVal}
/>
<IconButton color="primary" className={classes.iconBtn}> <IconButton color="primary" className={classes.iconBtn}>
<PhoneIcon fontSize="large" onClick={() => handleCall(inputVal)} /> <PhoneIcon fontSize="large" onClick={() => handleCall(inputVal)} />
</IconButton> </IconButton>
@@ -26,19 +26,8 @@ const DialerNavBar = () => {
}; };
return ( return (
<BottomNavigation <BottomNavigation value={page} onChange={handleChange} showLabels className={classes.root}>
value={page} <BottomNavigationAction label="History" value="/phone" component={NavLink} icon={<HistoryIcon />} to="/phone" />
onChange={handleChange}
showLabels
className={classes.root}
>
<BottomNavigationAction
label="History"
value="/phone"
component={NavLink}
icon={<HistoryIcon />}
to="/phone"
/>
<BottomNavigationAction <BottomNavigationAction
label="Dial" label="Dial"
value="/phone/dial" value="/phone/dial"
@@ -58,25 +58,17 @@ export const DialerHistory = ({ calls }) => {
{calls.map((call: ICall) => {calls.map((call: ICall) =>
call.transmitter === number ? ( call.transmitter === number ? (
<ListItem key={call.id} divider> <ListItem key={call.id} divider>
<ListItemIcon> <ListItemIcon>{<PhoneForwardedIcon className={classes.callForward} />}</ListItemIcon>
{<PhoneForwardedIcon className={classes.callForward} />}
</ListItemIcon>
<ListItemText <ListItemText
primary={getDisplayByNumber(call.receiver)} primary={getDisplayByNumber(call.receiver)}
secondary={dayjs.unix(call.start).format(t('DATE_TIME_FORMAT'))} secondary={dayjs.unix(call.start).format(t('DATE_TIME_FORMAT'))}
/> />
<IconButton onClick={() => handleCall(call.receiver)}> <IconButton onClick={() => handleCall(call.receiver)}>{<PhoneIcon />}</IconButton>
{<PhoneIcon />}
</IconButton>
{getDisplayByNumber(call.transmitter) === call.transmitter ? ( {getDisplayByNumber(call.transmitter) === call.transmitter ? (
<IconButton <IconButton
onClick={() => onClick={() => history.push(`/contacts/-1?addNumber=${call.transmitter}&referal=/phone/contacts`)}
history.push(
`/contacts/-1?addNumber=${call.transmitter}&referal=/phone/contacts`,
)
}
> >
{<PersonAddIcon />} {<PersonAddIcon />}
</IconButton> </IconButton>
@@ -84,25 +76,17 @@ export const DialerHistory = ({ calls }) => {
</ListItem> </ListItem>
) : ( ) : (
<ListItem key={call.id} divider> <ListItem key={call.id} divider>
<ListItemIcon> <ListItemIcon>{<PhoneCallbackIcon className={classes.callBack} />}</ListItemIcon>
{<PhoneCallbackIcon className={classes.callBack} />}
</ListItemIcon>
<ListItemText <ListItemText
primary={getDisplayByNumber(call.transmitter)} primary={getDisplayByNumber(call.transmitter)}
secondary={dayjs.unix(call.start).format(t('DATE_TIME_FORMAT'))} secondary={dayjs.unix(call.start).format(t('DATE_TIME_FORMAT'))}
/> />
<IconButton onClick={() => handleCall(call.transmitter)}> <IconButton onClick={() => handleCall(call.transmitter)}>{<PhoneIcon />}</IconButton>
{<PhoneIcon />}
</IconButton>
{getDisplayByNumber(call.transmitter) === call.transmitter ? ( {getDisplayByNumber(call.transmitter) === call.transmitter ? (
<IconButton <IconButton
onClick={() => onClick={() => history.push(`/contacts/-1?addNumber=${call.transmitter}&referal=/phone/contacts`)}
history.push(
`/contacts/-1?addNumber=${call.transmitter}&referal=/phone/contacts`,
)
}
> >
{<PersonAddIcon />} {<PersonAddIcon />}
</IconButton> </IconButton>
@@ -35,9 +35,7 @@ export const ExampleApp = () => {
<Button color="primary">{example.id}</Button> <Button color="primary">{example.id}</Button>
{/* Here we are using the value in a h3 tag */} {/* Here we are using the value in a h3 tag */}
<h3>{exampleString}</h3> <h3>{exampleString}</h3>
<IconButton onClick={() => (playing ? stop() : play())}> <IconButton onClick={() => (playing ? stop() : play())}>{playing ? <StopIcon /> : <PlayIcon />}</IconButton>
{playing ? <StopIcon /> : <PlayIcon />}
</IconButton>
<Button onClick={toggleSound}>Change sound on the fly</Button> <Button onClick={toggleSound}>Change sound on the fly</Button>
</AppContent> </AppContent>
</AppWrapper> </AppWrapper>
@@ -38,11 +38,7 @@ export const MessagesApp = () => {
/> />
</Switch> </Switch>
<Switch> <Switch>
<Route <Route exact path={['/messages/new/:phoneNumber', '/messages/new']} render={() => <MessageGroupModal />} />
exact
path={['/messages/new/:phoneNumber', '/messages/new']}
render={() => <MessageGroupModal />}
/>
</Switch> </Switch>
</AppContent> </AppContent>
<NewMessageGroupButton onClick={() => history.push('/messages/new')} /> <NewMessageGroupButton onClick={() => history.push('/messages/new')} />
@@ -32,9 +32,7 @@ const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => {
// handles phone numbers in a csv format and strips all spaces and // handles phone numbers in a csv format and strips all spaces and
// external characters out of them: // external characters out of them:
// 123-4567, 987-6543, 333-4444 // 123-4567, 987-6543, 333-4444
const phoneNumbers = participants.map(({ number }) => const phoneNumbers = participants.map(({ number }) => number.replace(/[^0-9]/g, ''));
number.replace(/[^0-9]/g, ''),
);
const labelValue = isGroupChat ? label.trim() : null; const labelValue = isGroupChat ? label.trim() : null;
if (phoneNumbers.length) { if (phoneNumbers.length) {
@@ -101,13 +99,7 @@ const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => {
</Box> </Box>
)} )}
<Box px={2} py={3}> <Box px={2} py={3}>
<Button <Button disabled={submitDisabled} variant="contained" fullWidth color="primary" type="submit">
disabled={submitDisabled}
variant="contained"
fullWidth
color="primary"
type="submit"
>
{t('APPS_MESSAGES_NEW_MESSAGE_GROUP_SUBMIT')} {t('APPS_MESSAGES_NEW_MESSAGE_GROUP_SUBMIT')}
</Button> </Button>
</Box> </Box>
@@ -1,10 +1,5 @@
import React from 'react'; import React from 'react';
import { import { ListItem, ListItemText, ListItemAvatar, Avatar as MuiAvatar } from '@material-ui/core';
ListItem,
ListItemText,
ListItemAvatar,
Avatar as MuiAvatar,
} from '@material-ui/core';
import { MessageGroup } from '../../../../common/typings/messages'; import { MessageGroup } from '../../../../common/typings/messages';
@@ -15,12 +10,7 @@ interface IProps {
const MessageGroupItem = ({ messageGroup, handleClick }: IProps): any => { const MessageGroupItem = ({ messageGroup, handleClick }: IProps): any => {
return ( return (
<ListItem <ListItem key={messageGroup.groupId} onClick={handleClick(messageGroup)} divider button>
key={messageGroup.groupId}
onClick={handleClick(messageGroup)}
divider
button
>
<ListItemAvatar> <ListItemAvatar>
<MuiAvatar src={messageGroup?.avatar} /> <MuiAvatar src={messageGroup?.avatar} />
</ListItemAvatar> </ListItemAvatar>
@@ -7,9 +7,7 @@ import useStyles from './list.styles';
interface IProps { interface IProps {
value: string; value: string;
handleChange: ( handleChange: (event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => void;
event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>,
) => void;
} }
const MessageSearch = ({ value, handleChange }: IProps) => { const MessageSearch = ({ value, handleChange }: IProps) => {
@@ -13,46 +13,30 @@ const MessagesList = (): any => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const { const { messageGroups, createMessageGroupResult, clearMessageGroupResult } = useMessages();
messageGroups,
createMessageGroupResult,
clearMessageGroupResult,
} = useMessages();
const [searchValue, setSearchValue] = useState(''); const [searchValue, setSearchValue] = useState('');
const goToConversation = useCallback( const goToConversation = useCallback(
(messageGroup) => (messageGroup) => history.push(`/messages/conversations/${messageGroup.groupId}/?${qs.stringify(messageGroup)}`),
history.push(
`/messages/conversations/${messageGroup.groupId}/?${qs.stringify(messageGroup)}`,
),
[history], [history],
); );
useEffect(() => { useEffect(() => {
if (createMessageGroupResult?.groupId) { if (createMessageGroupResult?.groupId) {
const findGroup = messageGroups.find( const findGroup = messageGroups.find((g) => g.groupId === createMessageGroupResult.groupId);
(g) => g.groupId === createMessageGroupResult.groupId,
);
clearMessageGroupResult(); clearMessageGroupResult();
if (findGroup) { if (findGroup) {
goToConversation(findGroup); goToConversation(findGroup);
} }
} }
}, [ }, [messageGroups, createMessageGroupResult, goToConversation, clearMessageGroupResult]);
messageGroups,
createMessageGroupResult,
goToConversation,
clearMessageGroupResult,
]);
if (!messageGroups) return null; if (!messageGroups) return null;
const handleClick = (messageGroup: MessageGroup) => () => { const handleClick = (messageGroup: MessageGroup) => () => {
Nui.send('phone:fetchMessages', { groupId: messageGroup.groupId }); Nui.send('phone:fetchMessages', { groupId: messageGroup.groupId });
history.push( history.push(`/messages/conversations/${messageGroup.groupId}/?${qs.stringify(messageGroup)}`);
`/messages/conversations/${messageGroup.groupId}/?${qs.stringify(messageGroup)}`,
);
}; };
const formattedSearch = searchValue.toLowerCase().trim(); const formattedSearch = searchValue.toLowerCase().trim();
@@ -62,25 +46,16 @@ const MessagesList = (): any => {
const displayIncludes = groupDisplay.includes(formattedSearch); const displayIncludes = groupDisplay.includes(formattedSearch);
const label = group.label?.toLowerCase(); const label = group.label?.toLowerCase();
return label return label ? displayIncludes || label.includes(formattedSearch) : displayIncludes;
? displayIncludes || label.includes(formattedSearch)
: displayIncludes;
}) })
: messageGroups; : messageGroups;
return ( return (
<> <>
<MessageSearch <MessageSearch value={searchValue} handleChange={(e) => setSearchValue(e.target.value)} />
value={searchValue}
handleChange={(e) => setSearchValue(e.target.value)}
/>
<List className={classes.root}> <List className={classes.root}>
{filteredGroups.map((messageGroup) => ( {filteredGroups.map((messageGroup) => (
<MessageGroupItem <MessageGroupItem key={messageGroup.groupId} messageGroup={messageGroup} handleClick={handleClick} />
key={messageGroup.groupId}
messageGroup={messageGroup}
handleClick={handleClick}
/>
))} ))}
</List> </List>
</> </>
@@ -38,17 +38,10 @@ const Conversation = ({ activeMessageGroup, messages }: IProps) => {
className={classes.overflowAutoY} className={classes.overflowAutoY}
> >
{messages.map((message) => ( {messages.map((message) => (
<MessageBubble <MessageBubble key={message.id} message={message} isGroupChat={activeMessageGroup?.isGroupChat} />
key={message.id}
message={message}
isGroupChat={activeMessageGroup?.isGroupChat}
/>
))} ))}
</Box> </Box>
<MessageInput <MessageInput messageGroupId={activeMessageGroup.groupId} onAddImageClick={() => setImageModalOpen(true)} />
messageGroupId={activeMessageGroup.groupId}
onAddImageClick={() => setImageModalOpen(true)}
/>
</> </>
); );
}; };
@@ -41,33 +41,21 @@ const isImage = (url) => {
return /(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|png|jpeg|gif)/g.test(url); return /(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|png|jpeg|gif)/g.test(url);
}; };
export const MessageBubble = ({ export const MessageBubble = ({ message, isGroupChat }: { message: Message; isGroupChat: boolean }) => {
message,
isGroupChat,
}: {
message: Message;
isGroupChat: boolean;
}) => {
const classes = useStyles(); const classes = useStyles();
return ( return (
<div> <div>
<Paper className={message.isMine ? classes.mySms : classes.sms} variant="outlined"> <Paper className={message.isMine ? classes.mySms : classes.sms} variant="outlined">
<Box> <Box>
{isImage(message.message) ? ( {isImage(message.message) ? (
<img <img src={message.message} className={classes.imageMessage} alt="multimedia" />
src={message.message}
className={classes.imageMessage}
alt="multimedia"
/>
) : ( ) : (
<div>{message.message}</div> <div>{message.message}</div>
)} )}
</Box> </Box>
<Box> <Box>
<Typography variant="subtitle1" color="secondary"> <Typography variant="subtitle1" color="secondary">
{isGroupChat && !message.isMine {isGroupChat && !message.isMine ? message.display || message.phone_number : null}
? message.display || message.phone_number
: null}
</Typography> </Typography>
</Box> </Box>
</Paper> </Paper>
@@ -89,10 +89,7 @@ export const MessageImageModal = ({ isOpen, messageGroupId, onClose, image }: IP
<Modal visible={queryParamImagePreview} handleClose={removeQueryParamImage}> <Modal visible={queryParamImagePreview} handleClose={removeQueryParamImage}>
<Box py={1}> <Box py={1}>
<Typography paragraph>Do you want to share this image?</Typography> <Typography paragraph>Do you want to share this image?</Typography>
<PictureResponsive <PictureResponsive src={queryParamImagePreview} alt={'Share gallery image preview'} />
src={queryParamImagePreview}
alt={'Share gallery image preview'}
/>
<Button <Button
fullWidth fullWidth
variant="contained" variant="contained"
@@ -75,13 +75,9 @@ export const MessageModal = () => {
// don't allow too many characters, it takes too much room // don't allow too many characters, it takes too much room
let header = activeMessageGroup ? activeMessageGroup.groupDisplay : ''; let header = activeMessageGroup ? activeMessageGroup.groupDisplay : '';
const truncatedHeader = `${header.slice(0, MAX_HEADER_CHARS).trim()}...`; const truncatedHeader = `${header.slice(0, MAX_HEADER_CHARS).trim()}...`;
header = header = header.length > MAX_HEADER_CHARS ? activeMessageGroup?.label || truncatedHeader : header;
header.length > MAX_HEADER_CHARS
? activeMessageGroup?.label || truncatedHeader
: header;
const headerClass = const headerClass = header.length > LARGE_HEADER_CHARS ? classes.largeGroupDisplay : classes.groupdisplay;
header.length > LARGE_HEADER_CHARS ? classes.largeGroupDisplay : classes.groupdisplay;
return ( return (
<Slide direction="left" in={!!activeMessageGroup}> <Slide direction="left" in={!!activeMessageGroup}>
@@ -6,9 +6,7 @@ import { useSnackbar } from '../../../ui/hooks/useSnackbar';
export const useMessagesService = () => { export const useMessagesService = () => {
const setMessageGroups = useSetRecoilState(messageState.messageGroups); const setMessageGroups = useSetRecoilState(messageState.messageGroups);
const setMessages = useSetRecoilState(messageState.messages); const setMessages = useSetRecoilState(messageState.messages);
const setCreateMessageGroupResult = useSetRecoilState( const setCreateMessageGroupResult = useSetRecoilState(messageState.createMessageGroupResult);
messageState.createMessageGroupResult,
);
const { addAlert } = useSnackbar(); const { addAlert } = useSnackbar();
useNuiEvent('MESSAGES', 'phone:fetchMessageGroupsSuccess', setMessageGroups); useNuiEvent('MESSAGES', 'phone:fetchMessageGroupsSuccess', setMessageGroups);
+2 -9
View File
@@ -1,9 +1,5 @@
import { useRecoilState, useRecoilValue } from 'recoil'; import { useRecoilState, useRecoilValue } from 'recoil';
import { import { CreateMessageGroupResult, Message, MessageGroup } from '../../../common/typings/messages';
CreateMessageGroupResult,
Message,
MessageGroup,
} from '../../../common/typings/messages';
import { messageState } from './state'; import { messageState } from './state';
interface IUseMessages { interface IUseMessages {
@@ -18,10 +14,7 @@ export default (): IUseMessages => {
const [messages, setMessages] = useRecoilState<Message[] | null>(messageState.messages); const [messages, setMessages] = useRecoilState<Message[] | null>(messageState.messages);
const messageGroups = useRecoilValue<MessageGroup[] | null>(messageState.messageGroups); const messageGroups = useRecoilValue<MessageGroup[] | null>(messageState.messageGroups);
const [ const [createMessageGroupResult, setCreateMessageGroupResult] = useRecoilState<CreateMessageGroupResult | null>(
createMessageGroupResult,
setCreateMessageGroupResult,
] = useRecoilState<CreateMessageGroupResult | null>(
messageState.createMessageGroupResult, messageState.createMessageGroupResult,
); );
+4 -25
View File
@@ -1,13 +1,4 @@
import { import { Button, TextField, Slide, Paper, Typography, Container, CircularProgress, Box } from '@material-ui/core';
Button,
TextField,
Slide,
Paper,
Typography,
Container,
CircularProgress,
Box,
} from '@material-ui/core';
import React from 'react'; import React from 'react';
import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import { useNoteDetail } from '../hooks/useNoteDetail'; import { useNoteDetail } from '../hooks/useNoteDetail';
@@ -109,11 +100,7 @@ export const NoteModal = () => {
</Button> </Button>
</Box> </Box>
<Box display="inline" p={1}> <Box display="inline" p={1}>
<StatusButton <StatusButton color="error" variant="contained" onClick={_handleClose}>
color="error"
variant="contained"
onClick={_handleClose}
>
{t('GENERIC_CANCEL')} {t('GENERIC_CANCEL')}
</StatusButton> </StatusButton>
</Box> </Box>
@@ -121,20 +108,12 @@ export const NoteModal = () => {
) : ( ) : (
<> <>
<Box display="inline" p={1}> <Box display="inline" p={1}>
<Button <Button color="primary" variant="contained" onClick={handleUpdateNote}>
color="primary"
variant="contained"
onClick={handleUpdateNote}
>
{t('GENERIC_UPDATE')} {t('GENERIC_UPDATE')}
</Button> </Button>
</Box> </Box>
<Box display="inline" p={1}> <Box display="inline" p={1}>
<StatusButton <StatusButton color="error" variant="contained" onClick={handleDeleteNote}>
color="error"
variant="contained"
onClick={handleDeleteNote}
>
{t('GENERIC_DELETE')} {t('GENERIC_DELETE')}
</StatusButton> </StatusButton>
</Box> </Box>
@@ -54,10 +54,7 @@ export const SelloutItem = (listing) => {
<Typography className={classes.headerTypo} variant="h5"> <Typography className={classes.headerTypo} variant="h5">
{listing.name} {listing.name}
</Typography> </Typography>
<Typography <Typography className={classes.headerTypo} style={{ borderBottom: '1px solid #f44336' }}>
className={classes.headerTypo}
style={{ borderBottom: '1px solid #f44336' }}
>
{listing.number} {listing.number}
</Typography> </Typography>
<Typography variant="h5" style={{ padding: 5 }}> <Typography variant="h5" style={{ padding: 5 }}>
@@ -28,16 +28,8 @@ export const NavigationBar = () => {
showLabels showLabels
className={classes.root} className={classes.root}
> >
<BottomNavigationAction <BottomNavigationAction component={Link} icon={<FontAwesomeIcon icon={faHome} />} to="/sellout" />
component={Link} <BottomNavigationAction component={Link} icon={<AddCircleIcon />} to="/sellout/new" />
icon={<FontAwesomeIcon icon={faHome} />}
to="/sellout"
/>
<BottomNavigationAction
component={Link}
icon={<AddCircleIcon />}
to="/sellout/new"
/>
</BottomNavigation> </BottomNavigation>
); );
}; };
@@ -10,15 +10,7 @@ import { useApp } from '../../../os/apps/hooks/useApps';
import { SettingItem } from './SettingItem'; import { SettingItem } from './SettingItem';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import { Brush, Wallpaper, Phone, Smartphone, ZoomIn, LibraryMusic, VolumeUp } from '@material-ui/icons';
Brush,
Wallpaper,
Phone,
Smartphone,
ZoomIn,
LibraryMusic,
VolumeUp,
} from '@material-ui/icons';
import { import {
Box, Box,
@@ -53,11 +45,7 @@ export const SettingsApp = () => {
useEffect(() => { useEffect(() => {
setSliders((curr) => { setSliders((curr) => {
if (!curr.length) { if (!curr.length) {
return [ return [settings.ringtoneVol, settings.notificationVol, settings.TWITTER_notificationVol];
settings.ringtoneVol,
settings.notificationVol,
settings.TWITTER_notificationVol,
];
} }
return curr; return curr;
}); });
@@ -74,9 +62,7 @@ export const SettingsApp = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const wallpapers = config.wallpapers.map( const wallpapers = config.wallpapers.map(
MapStringOptions(settings.wallpaper, (val: string) => MapStringOptions(settings.wallpaper, (val: string) => handleSettingChange('wallpaper', val)),
handleSettingChange('wallpaper', val),
),
); );
const frames = config.frames.map( const frames = config.frames.map(
MapStringOptions(settings.frame, (val: string) => handleSettingChange('frame', val)), MapStringOptions(settings.frame, (val: string) => handleSettingChange('frame', val)),
@@ -88,20 +74,14 @@ export const SettingsApp = () => {
MapStringOptions(settings.zoom, (val: string) => handleSettingChange('zoom', val)), MapStringOptions(settings.zoom, (val: string) => handleSettingChange('zoom', val)),
); );
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),
),
); );
const notifications = config.notifications.map( const notifications = config.notifications.map(
MapStringOptions(settings.notification, (val: string) => MapStringOptions(settings.notification, (val: string) => handleSettingChange('notification', val)),
handleSettingChange('notification', val),
),
); );
const twitterNotifications = config.notifications.map( const twitterNotifications = config.notifications.map(
MapStringOptions(settings.notification, (val: string) => MapStringOptions(settings.notification, (val: string) => handleSettingChange('TWITTER_notification', val)),
handleSettingChange('TWITTER_notification', val),
),
); );
const [openMenu, closeMenu, ContextMenu, isMenuOpen] = useContextMenu(); const [openMenu, closeMenu, ContextMenu, isMenuOpen] = useContextMenu();
@@ -110,11 +90,7 @@ export const SettingsApp = () => {
<AppTitle app={settingsApp} /> <AppTitle app={settingsApp} />
<AppContent backdrop={isMenuOpen} onClickBackdrop={closeMenu}> <AppContent backdrop={isMenuOpen} onClickBackdrop={closeMenu}>
<List disablePadding subheader={<SubHeaderComp text="Phone" />}> <List disablePadding subheader={<SubHeaderComp text="Phone" />}>
<SettingItem <SettingItem label={t('APPS_SETTINGS_PHONE_NUMBER')} value={simcard.number} icon={<Phone />} />
label={t('APPS_SETTINGS_PHONE_NUMBER')}
value={simcard.number}
icon={<Phone />}
/>
<SettingItem <SettingItem
label={t('APPS_SETTINGS_OPTION_RINGTONE')} label={t('APPS_SETTINGS_OPTION_RINGTONE')}
value={settings.ringtone} value={settings.ringtone}
@@ -126,10 +102,7 @@ export const SettingsApp = () => {
<ListItemIcon> <ListItemIcon>
<VolumeUp /> <VolumeUp />
</ListItemIcon> </ListItemIcon>
<ListItemText <ListItemText primary={t('APPS_SETTINGS_OPTION_RINGTONEVOL')} secondary={settings.ringtoneVol} />
primary={t('APPS_SETTINGS_OPTION_RINGTONEVOL')}
secondary={settings.ringtoneVol}
/>
<ListItemSecondaryAction> <ListItemSecondaryAction>
<Box p={2} width={150}> <Box p={2} width={150}>
<Slider <Slider
@@ -153,10 +126,7 @@ export const SettingsApp = () => {
<ListItemIcon> <ListItemIcon>
<VolumeUp /> <VolumeUp />
</ListItemIcon> </ListItemIcon>
<ListItemText <ListItemText primary={t('APPS_SETTINGS_OPTION_NOTIFICATIONVOL')} secondary={settings.notificationVol} />
primary={t('APPS_SETTINGS_OPTION_NOTIFICATIONVOL')}
secondary={settings.notificationVol}
/>
<ListItemSecondaryAction> <ListItemSecondaryAction>
<Box p={2} width={150}> <Box p={2} width={150}>
<Slider <Slider
@@ -164,9 +134,7 @@ export const SettingsApp = () => {
min={0} min={0}
max={100} max={100}
onChange={handleSliderChange(1)} onChange={handleSliderChange(1)}
onChangeCommitted={() => onChangeCommitted={() => handleSettingChange('notificationVol', sliders[1])}
handleSettingChange('notificationVol', sliders[1])
}
/> />
</Box> </Box>
</ListItemSecondaryAction> </ListItemSecondaryAction>
@@ -226,9 +194,7 @@ export const SettingsApp = () => {
min={0} min={0}
max={100} max={100}
onChange={handleSliderChange(2)} onChange={handleSliderChange(2)}
onChangeCommitted={() => onChangeCommitted={() => handleSettingChange('TWITTER_notificationVol', sliders[2])}
handleSettingChange('TWITTER_notificationVol', sliders[2])
}
/> />
</Box> </Box>
</ListItemSecondaryAction> </ListItemSecondaryAction>
@@ -1,5 +1,3 @@
export const getRingtonePath = (name?: string) => export const getRingtonePath = (name?: string) => `./media/ringtones/${name || 'pixel'}.ogg`;
`./media/ringtones/${name || 'pixel'}.ogg`;
export const getNotificationPath = (name?: string) => export const getNotificationPath = (name?: string) => `./media/notifications/${name || 'online'}.ogg`;
`./media/notifications/${name || 'online'}.ogg`;
@@ -106,10 +106,7 @@ export const AddTweetModal = () => {
const data = { const data = {
message, message,
images: images: images && images.length > 0 ? images.map((image) => image.link).join(IMAGE_DELIMITER) : '',
images && images.length > 0
? images.map((image) => image.link).join(IMAGE_DELIMITER)
: '',
realUser: 'testUser', realUser: 'testUser',
}; };
Nui.send('phone:createTweet', data); Nui.send('phone:createTweet', data);
@@ -158,27 +155,13 @@ export const AddTweetModal = () => {
return ( return (
<Modal visible={modalVisible} handleClose={_handleClose}> <Modal visible={modalVisible} handleClose={_handleClose}>
<TweetMessage <TweetMessage modalVisible={modalVisible} message={message} handleChange={handleMessageChange} />
modalVisible={modalVisible} <ImagePrompt visible={showImagePrompt} value={link} handleChange={handleimageChange} />
message={message}
handleChange={handleMessageChange}
/>
<ImagePrompt
visible={showImagePrompt}
value={link}
handleChange={handleimageChange}
/>
<EmojiSelect visible={showEmoji} onEmojiClick={handleSelectEmoji} /> <EmojiSelect visible={showEmoji} onEmojiClick={handleSelectEmoji} />
<ImageDisplay <ImageDisplay visible={!showEmoji && images.length > 0} images={images} removeImage={removeImage} />
visible={!showEmoji && images.length > 0}
images={images}
removeImage={removeImage}
/>
<div className={classes.buttonsContainer}> <div className={classes.buttonsContainer}>
<IconButtons <IconButtons
onImageClick={ onImageClick={images.length < config.twitter.maxImages ? toggleShowImagePrompt : null}
images.length < config.twitter.maxImages ? toggleShowImagePrompt : null
}
onEmojiClick={toggleShowEmoji} onEmojiClick={toggleShowEmoji}
/> />
<ControlButtons <ControlButtons
@@ -18,16 +18,8 @@ export function TwitterBottomNavigation({ activePage, handleChange }) {
return ( return (
<BottomNavigation value={activePage} onChange={handleChange} className={classes.root}> <BottomNavigation value={activePage} onChange={handleChange} className={classes.root}>
<BottomNavigationAction component={Link} to="/twitter" icon={<HomeIcon />} /> <BottomNavigationAction component={Link} to="/twitter" icon={<HomeIcon />} />
<BottomNavigationAction <BottomNavigationAction component={Link} to="/twitter/search" icon={<SearchIcon />} />
component={Link} <BottomNavigationAction component={Link} to="/twitter/profile" icon={<ProfileIcon />} />
to="/twitter/search"
icon={<SearchIcon />}
/>
<BottomNavigationAction
component={Link}
to="/twitter/profile"
icon={<ProfileIcon />}
/>
</BottomNavigation> </BottomNavigation>
); );
} }
@@ -59,8 +59,7 @@ export const TwitterApp = () => {
// before any other action can be taken by the user we force // before any other action can be taken by the user we force
// them have a profile name // them have a profile name
const promptProfileName = const promptProfileName = profile && (!profile.profile_name || !profile.profile_name.trim());
profile && (!profile.profile_name || !profile.profile_name.trim());
const openModal = () => setModalVisible(true); const openModal = () => setModalVisible(true);
const handlePageChange = (e, page) => setActivePage(page); const handlePageChange = (e, page) => setActivePage(page);
@@ -83,9 +82,7 @@ export const TwitterApp = () => {
)} )}
</AppContent> </AppContent>
{showTweetButton && <TweetButton openModal={openModal} />} {showTweetButton && <TweetButton openModal={openModal} />}
{!promptProfileName && ( {!promptProfileName && <BottomNavigation activePage={activePage} handleChange={handlePageChange} />}
<BottomNavigation activePage={activePage} handleChange={handlePageChange} />
)}
</AppWrapper> </AppWrapper>
); );
}; };
@@ -16,19 +16,12 @@ const useStyles = makeStyles((theme) => ({
}, },
})); }));
export const ControlButtons = ({ export const ControlButtons = ({ showImagePrompt, showEmoji, onCloseClick, onPrimaryClick }) => {
showImagePrompt,
showEmoji,
onCloseClick,
onPrimaryClick,
}) => {
const classes = useStyles(); const classes = useStyles();
const { t } = useTranslation(); const { t } = useTranslation();
const imagePromptVisible = showImagePrompt && !showEmoji; const imagePromptVisible = showImagePrompt && !showEmoji;
const primaryButtonText = imagePromptVisible const primaryButtonText = imagePromptVisible ? t('APPS_TWITTER_SUBMIT_IMAGE') : t('APPS_TWITTER_TWEET');
? t('APPS_TWITTER_SUBMIT_IMAGE')
: t('APPS_TWITTER_TWEET');
const showCloseButton = showImagePrompt || showEmoji; const showCloseButton = showImagePrompt || showEmoji;
return ( return (
@@ -37,12 +30,7 @@ export const ControlButtons = ({
{primaryButtonText} {primaryButtonText}
</Button> </Button>
{showCloseButton && ( {showCloseButton && (
<Button <Button className={classes.close} variant="contained" color="secondary" onClick={onCloseClick}>
className={classes.close}
variant="contained"
color="secondary"
onClick={onCloseClick}
>
{t('APPS_TWITTER_CLOSE_IMAGE')} {t('APPS_TWITTER_CLOSE_IMAGE')}
</Button> </Button>
)} )}
@@ -28,11 +28,7 @@ function LikeButton({ tweetId, isLiked }) {
); );
} }
return ( return <Button onClick={handleClick}>{liked ? <FavoriteIcon /> : <FavoriteBorderIcon />}</Button>;
<Button onClick={handleClick}>
{liked ? <FavoriteIcon /> : <FavoriteBorderIcon />}
</Button>
);
} }
export default LikeButton; export default LikeButton;
@@ -35,12 +35,7 @@ export function ProfileUpdateButton({ handleClick }) {
return ( return (
<div className={classes.root}> <div className={classes.root}>
<Fab <Fab className={classes.button} color="primary" onClick={handleClick} disabled={isLoading}>
className={classes.button}
color="primary"
onClick={handleClick}
disabled={isLoading}
>
<PublishIcon /> <PublishIcon />
</Fab> </Fab>
</div> </div>
@@ -45,11 +45,7 @@ export const Image = ({ link, handleClick, small }) => {
<CloseIcon /> <CloseIcon />
</IconButton> </IconButton>
)} )}
<img <img alt="small avatar" className={small ? classes.imgSmall : classes.img} src={link} />
alt="small avatar"
className={small ? classes.imgSmall : classes.img}
src={link}
/>
</div> </div>
); );
}; };
@@ -23,9 +23,7 @@ export const ImagePrompt = ({ visible, value, handleChange }) => {
textFieldRef.current && textFieldRef.current.focus(); textFieldRef.current && textFieldRef.current.focus();
}, [visible]); }, [visible]);
const handleImageChange = useCallback((e) => handleChange(e.target.value), [ const handleImageChange = useCallback((e) => handleChange(e.target.value), [handleChange]);
handleChange,
]);
if (!visible) return null; if (!visible) return null;
return ( return (
@@ -70,22 +70,13 @@ export function Profile() {
handleChange={handleNameChange} handleChange={handleNameChange}
allowChange={allowEdtiableProfileName} allowChange={allowEdtiableProfileName}
/> />
<ProfileField <ProfileField label={t('APPS_TWITTER_EDIT_PROFILE_BIO')} value={bio} handleChange={handleBioChange} multiline />
label={t('APPS_TWITTER_EDIT_PROFILE_BIO')}
value={bio}
handleChange={handleBioChange}
multiline
/>
<ProfileField <ProfileField
label={t('APPS_TWITTER_EDIT_PROFILE_LOCATION')} label={t('APPS_TWITTER_EDIT_PROFILE_LOCATION')}
value={location} value={location}
handleChange={handleLocationChange} handleChange={handleLocationChange}
/> />
<ProfileField <ProfileField label={t('APPS_TWITTER_EDIT_PROFILE_JOB')} value={job} handleChange={handleJobChange} />
label={t('APPS_TWITTER_EDIT_PROFILE_JOB')}
value={job}
handleChange={handleJobChange}
/>
<ProfileUpdateButton handleClick={handleUpdate} /> <ProfileUpdateButton handleClick={handleUpdate} />
</div> </div>
); );
@@ -76,12 +76,8 @@ export const ShowMore = ({ id, isReported, isMine }) => {
horizontal: 'left', horizontal: 'left',
}} }}
> >
{allowedToDelete && ( {allowedToDelete && <MenuItem onClick={handleDeleteTweet}>{t('APPS_TWITTER_DELETE')}</MenuItem>}
<MenuItem onClick={handleDeleteTweet}>{t('APPS_TWITTER_DELETE')}</MenuItem> {allowedToReport && <ReportButton handleClose={handleClose} isReported={isReported} tweetId={id} />}
)}
{allowedToReport && (
<ReportButton handleClose={handleClose} isReported={isReported} tweetId={id} />
)}
</Menu> </Menu>
</> </>
); );
@@ -1,12 +1,7 @@
import React, { memo } from 'react'; import React, { memo } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { makeStyles } from '@material-ui/core/styles'; import { makeStyles } from '@material-ui/core/styles';
import { import { ListItemAvatar, Avatar as MuiAvatar, ListItem, Typography } from '@material-ui/core';
ListItemAvatar,
Avatar as MuiAvatar,
ListItem,
Typography,
} from '@material-ui/core';
import { secondsToHumanReadable } from '../../utils/time'; import { secondsToHumanReadable } from '../../utils/time';
import LikeButton from '../buttons/LikeButton'; import LikeButton from '../buttons/LikeButton';
import ReplyButton from '../buttons/ReplyButton'; import ReplyButton from '../buttons/ReplyButton';
@@ -61,17 +56,7 @@ const useStyles = makeStyles(() => ({
})); }));
export const Tweet = (tweet) => { export const Tweet = (tweet) => {
const { const { id, message, images, avatar_url, profile_name, seconds_since_tweet, isLiked, isMine, isReported } = tweet;
id,
message,
images,
avatar_url,
profile_name,
seconds_since_tweet,
isLiked,
isMine,
isReported,
} = tweet;
const classes = useStyles(); const classes = useStyles();
const { t } = useTranslation(); const { t } = useTranslation();
const { config } = usePhone(); const { config } = usePhone();
@@ -105,12 +90,7 @@ export const Tweet = (tweet) => {
<div className={classes.content}> <div className={classes.content}>
<div className={classes.primary}> <div className={classes.primary}>
<div className={classes.profile}>{profileName}</div> <div className={classes.profile}>{profileName}</div>
<Typography <Typography className={classes.date} component="div" variant="body2" color="textSecondary">
className={classes.date}
component="div"
variant="body2"
color="textSecondary"
>
{secondsToHumanReadable(t, seconds_since_tweet)} {secondsToHumanReadable(t, seconds_since_tweet)}
</Typography> </Typography>
</div> </div>
@@ -51,14 +51,10 @@ export const TweetMessage = ({ modalVisible, message, handleChange }) => {
let errorMessage = null; let errorMessage = null;
const overCharacterLimit = message.trim().length > characterLimit; const overCharacterLimit = message.trim().length > characterLimit;
const characterWarningPrompt = `${t( const characterWarningPrompt = `${t('APPS_TWITTER_TWEET_MESSAGE_CHAR_LIMIT')} (${characterLimit})`;
'APPS_TWITTER_TWEET_MESSAGE_CHAR_LIMIT',
)} (${characterLimit})`;
const overNewLineLimit = getNewLineCount(message) > newLineLimit; const overNewLineLimit = getNewLineCount(message) > newLineLimit;
const newLineWarningPrompt = `${t( const newLineWarningPrompt = `${t('APPS_TWITTER_TWEET_MESSAGE_NEW_LINE_LIMIT')} (${newLineLimit})`;
'APPS_TWITTER_TWEET_MESSAGE_NEW_LINE_LIMIT',
)} (${newLineLimit})`;
if (overCharacterLimit) { if (overCharacterLimit) {
errorMessage = characterWarningPrompt; errorMessage = characterWarningPrompt;
+1 -3
View File
@@ -2,9 +2,7 @@ import { useRecoilState } from 'recoil';
import { twitterState } from './state'; import { twitterState } from './state';
export const useModal = () => { export const useModal = () => {
const [modalVisible, setModalVisible] = useRecoilState( const [modalVisible, setModalVisible] = useRecoilState(twitterState.showCreateTweetModal);
twitterState.showCreateTweetModal,
);
const [message, setMessage] = useRecoilState(twitterState.modalMessage); const [message, setMessage] = useRecoilState(twitterState.modalMessage);
return { modalVisible, setModalVisible, message, setMessage }; return { modalVisible, setModalVisible, message, setMessage };
}; };
+1 -3
View File
@@ -19,9 +19,7 @@ interface IUseProfile {
export const useProfile = (): IUseProfile => { export const useProfile = (): IUseProfile => {
const profile = useRecoilValue(twitterState.profile); const profile = useRecoilValue(twitterState.profile);
const updateProfileLoading = useRecoilValue(twitterState.updateProfileLoading); const updateProfileLoading = useRecoilValue(twitterState.updateProfileLoading);
const [updateProfileSuccessful, setUpdateProfileSuccessful] = useRecoilState( const [updateProfileSuccessful, setUpdateProfileSuccessful] = useRecoilState(twitterState.updateProfileSuccess);
twitterState.updateProfileSuccess,
);
return { return {
profile, profile,
updateProfileLoading, updateProfileLoading,
@@ -4,9 +4,7 @@ import { twitterState } from './state';
export const useTweetStatus = () => { export const useTweetStatus = () => {
const createTweetLoading = useRecoilValue(twitterState.createTweetLoading); const createTweetLoading = useRecoilValue(twitterState.createTweetLoading);
const [createTweetSuccessful, setCreateTweetSuccessful] = useRecoilState( const [createTweetSuccessful, setCreateTweetSuccessful] = useRecoilState(twitterState.createTweetSuccessful);
twitterState.createTweetSuccessful,
);
return { return {
createTweetLoading, createTweetLoading,
createTweetSuccessful, createTweetSuccessful,
+1 -4
View File
@@ -12,10 +12,7 @@ const DAYS = 'APPS_TWITTER_TIME_DAYS';
* @param {function} t - translation object passed from a component implementing the hook * @param {function} t - translation object passed from a component implementing the hook
* @param {number} seconds - seconds to translate to a string * @param {number} seconds - seconds to translate to a string
*/ */
export function secondsToHumanReadable( export function secondsToHumanReadable(t: (input: string) => string, seconds: number): string {
t: (input: string) => string,
seconds: number,
): string {
if (seconds < 60) { if (seconds < 60) {
return t(JUST_NOW); return t(JUST_NOW);
} else if (seconds < ONE_HOUR) { } else if (seconds < ONE_HOUR) {
@@ -6,10 +6,7 @@ interface IRouterLocation {
search: any; search: any;
} }
export const deleteQueryFromLocation = ( export const deleteQueryFromLocation = (location: Record<string, unknown> & IRouterLocation, key = '') => {
location: Record<string, unknown> & IRouterLocation,
key = '',
) => {
const { query } = url(location.pathname + location.search); const { query } = url(location.pathname + location.search);
return `${location.pathname}/?${qs.stringify({ return `${location.pathname}/?${qs.stringify({
...query, ...query,
+1 -9
View File
@@ -19,15 +19,7 @@
"printDebugLogs": true, "printDebugLogs": true,
"logLevel": 1 "logLevel": 1
}, },
"frames": [ "frames": ["default.png", "blue.png", "gold.png", "kawaii.png", "minimal.png", "pink.png", "white.png"],
"default.png",
"blue.png",
"gold.png",
"kawaii.png",
"minimal.png",
"pink.png",
"white.png"
],
"zoomOptions": [1, 0.9, 0.8], "zoomOptions": [1, 0.9, 0.8],
"ringtones": ["marimba", "pixel"], "ringtones": ["marimba", "pixel"],
"notifications": ["online", "99kr"], "notifications": ["online", "99kr"],
+2 -2
View File
@@ -1,6 +1,6 @@
body { body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans',
'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; 'Droid Sans', 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
font-size: 20px; font-size: 20px;
+7 -30
View File
@@ -1,13 +1,7 @@
import React from 'react'; import React from 'react';
import { blue, common, grey, purple } from '@material-ui/core/colors'; import { blue, common, grey, purple } from '@material-ui/core/colors';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { import { faAd, faPlaneArrival, faPhoneAlt, faWonSign, faStickyNote } from '@fortawesome/free-solid-svg-icons';
faAd,
faPlaneArrival,
faPhoneAlt,
faWonSign,
faStickyNote,
} from '@fortawesome/free-solid-svg-icons';
import { faTwitter } from '@fortawesome/free-brands-svg-icons'; import { faTwitter } from '@fortawesome/free-brands-svg-icons';
import ContactsIcon from '@material-ui/icons/Contacts'; import ContactsIcon from '@material-ui/icons/Contacts';
@@ -28,26 +22,11 @@ import { NotesApp } from '../../../apps/notes/NotesApp';
import CameraApp from '../../../apps/camera/components/CameraApp'; import CameraApp from '../../../apps/camera/components/CameraApp';
import { AppRoute } from '../components/AppRoute'; import { AppRoute } from '../components/AppRoute';
import { import { MESSAGES_APP_PRIMARY_COLOR, MESSAGES_APP_TEXT_COLOR } from '../../../apps/messages/messages.theme';
MESSAGES_APP_PRIMARY_COLOR, import { CONTACTS_APP_PRIMARY_COLOR, CONTACTS_APP_TEXT_COLOR } from '../../../apps/contacts/contacts.theme';
MESSAGES_APP_TEXT_COLOR, import { SELLOUT_APP_PRIMARY_COLOR, SELLOUT_APP_ICON_COLOR } from '../../../apps/sellout/sellout.theme';
} from '../../../apps/messages/messages.theme'; import { NOTES_APP_ICON_COLOR, NOTES_APP_PRIMARY_COLOR } from '../../../apps/notes/notes.theme';
import { import { DIALER_APP_PRIMARY_COLOR, DIALER_APP_TEXT_COLOR } from '../../../apps/dialer/dialer.theme';
CONTACTS_APP_PRIMARY_COLOR,
CONTACTS_APP_TEXT_COLOR,
} from '../../../apps/contacts/contacts.theme';
import {
SELLOUT_APP_PRIMARY_COLOR,
SELLOUT_APP_ICON_COLOR,
} from '../../../apps/sellout/sellout.theme';
import {
NOTES_APP_ICON_COLOR,
NOTES_APP_PRIMARY_COLOR,
} from '../../../apps/notes/notes.theme';
import {
DIALER_APP_PRIMARY_COLOR,
DIALER_APP_TEXT_COLOR,
} from '../../../apps/dialer/dialer.theme';
export interface IAppConfig { export interface IAppConfig {
id: string; id: string;
@@ -99,9 +78,7 @@ export const APPS: IAppConfig[] = [
backgroundColor: purple[500], backgroundColor: purple[500],
color: grey[50], color: grey[50],
path: '/calculator', path: '/calculator',
Route: () => ( Route: () => <AppRoute id="CALCULATOR" path="/calculator" component={CalculatorApp} />,
<AppRoute id="CALCULATOR" path="/calculator" component={CalculatorApp} />
),
}, },
{ {
id: 'SETTINGS', id: 'SETTINGS',
+1 -4
View File
@@ -12,10 +12,7 @@ export const useApps = () => {
})), })),
[icons], [icons],
); );
const getApp = useCallback( const getApp = useCallback((id: string): IAppConfig => apps.find((a) => a.id === id) || null, [apps]);
(id: string): IAppConfig => apps.find((a) => a.id === id) || null,
[apps],
);
return { apps, getApp }; return { apps, getApp };
}; };
+1 -3
View File
@@ -5,9 +5,7 @@ import { callerState } from './state';
export const useDuration = () => { export const useDuration = () => {
const [duration, setDuration] = useRecoilState(callerState.callDuration); const [duration, setDuration] = useRecoilState(callerState.callDuration);
const resetDuration = useCallback(() => setDuration({ ms: 0, s: 0, m: 0, h: 0 }), [ const resetDuration = useCallback(() => setDuration({ ms: 0, s: 0, m: 0, h: 0 }), [setDuration]);
setDuration,
]);
return { duration, setDuration, resetDuration }; return { duration, setDuration, resetDuration };
}; };
@@ -34,15 +34,7 @@ const keyboardState = {
}), }),
}; };
const validKeys = [ const validKeys = ['ArrowRight', 'ArrowLeft', 'ArrowUp', 'ArrowDown', 'Backspace', 'Enter', 'Escape'];
'ArrowRight',
'ArrowLeft',
'ArrowUp',
'ArrowDown',
'Backspace',
'Enter',
'Escape',
];
const isKeyValid = (key) => validKeys.indexOf(key) !== -1; const isKeyValid = (key) => validKeys.indexOf(key) !== -1;
@@ -28,16 +28,8 @@ export const Navigation = () => {
value(); value();
}} }}
> >
<BottomNavigationAction <BottomNavigationAction label="Home" value={() => history.push('/')} icon={<AppsIcon />} />
label="Home" <BottomNavigationAction label="Close" value={closePhone} icon={<RadioButtonUncheckedIcon />} />
value={() => history.push('/')}
icon={<AppsIcon />}
/>
<BottomNavigationAction
label="Close"
value={closePhone}
icon={<RadioButtonUncheckedIcon />}
/>
<BottomNavigationAction <BottomNavigationAction
label="Back" label="Back"
value={() => !isExact && history.goBack()} value={() => !isExact && history.goBack()}
@@ -1,15 +1,5 @@
import React from 'react'; import React from 'react';
import { import { makeStyles, Typography, Grid, IconButton, Slide, Paper, Box, List, Divider } from '@material-ui/core';
makeStyles,
Typography,
Grid,
IconButton,
Slide,
Paper,
Box,
List,
Divider,
} from '@material-ui/core';
import SignalIcon from '@material-ui/icons/SignalCellular3Bar'; import SignalIcon from '@material-ui/icons/SignalCellular3Bar';
import Battery90Icon from '@material-ui/icons/Battery90'; import Battery90Icon from '@material-ui/icons/Battery90';
import ArrowDropUpIcon from '@material-ui/icons/ArrowDropUp'; import ArrowDropUpIcon from '@material-ui/icons/ArrowDropUp';
@@ -66,13 +56,7 @@ const useStyles = makeStyles((theme) => ({
export const NotificationBar = () => { export const NotificationBar = () => {
const classes = useStyles(); const classes = useStyles();
const { const { icons, notifications, removeNotification, barUncollapsed, setBarUncollapsed } = useNotifications();
icons,
notifications,
removeNotification,
barUncollapsed,
setBarUncollapsed,
} = useNotifications();
return ( return (
<> <>
@@ -87,12 +71,7 @@ export const NotificationBar = () => {
> >
<Grid container item wrap="nowrap"> <Grid container item wrap="nowrap">
{icons.map((notifIcon) => ( {icons.map((notifIcon) => (
<Grid <Grid item key={notifIcon.key} component={IconButton} className={classes.icon}>
item
key={notifIcon.key}
component={IconButton}
className={classes.icon}
>
{notifIcon.icon} {notifIcon.icon}
</Grid> </Grid>
))} ))}
@@ -139,11 +118,7 @@ export const NotificationBar = () => {
</List> </List>
</Box> </Box>
<Box display="flex"> <Box display="flex">
<IconButton <IconButton className={classes.collapseBtn} size="small" onClick={() => setBarUncollapsed(false)}>
className={classes.collapseBtn}
size="small"
onClick={() => setBarUncollapsed(false)}
>
<ArrowDropUpIcon /> <ArrowDropUpIcon />
</IconButton> </IconButton>
</Box> </Box>
@@ -1,13 +1,6 @@
import React from 'react'; import React from 'react';
import CloseIcon from '@material-ui/icons/Close'; import CloseIcon from '@material-ui/icons/Close';
import { import { IconButton, ListItem, ListItemAvatar, ListItemText, makeStyles, Theme } from '@material-ui/core';
IconButton,
ListItem,
ListItemAvatar,
ListItemText,
makeStyles,
Theme,
} from '@material-ui/core';
import { INotification } from '../providers/NotificationsProvider'; import { INotification } from '../providers/NotificationsProvider';
const useStyles = makeStyles<Theme, { cantClose: boolean }>((theme) => ({ const useStyles = makeStyles<Theme, { cantClose: boolean }>((theme) => ({
@@ -25,9 +25,7 @@ const unshiftApp = (arr: IAppConfig[], app) => {
export const useQuickAccess = () => { export const useQuickAccess = () => {
const history = useHistory(); const history = useHistory();
const { apps, getApp } = useApps(); const { apps, getApp } = useApps();
const [recentlyUsed, setRecentlyUsed] = useRecoilState<IAppConfig[]>( const [recentlyUsed, setRecentlyUsed] = useRecoilState<IAppConfig[]>(state.recentlyUsed);
state.recentlyUsed,
);
useEffect(() => { useEffect(() => {
setRecentlyUsed([getApp('SETTINGS')]); setRecentlyUsed([getApp('SETTINGS')]);
@@ -1,11 +1,4 @@
import React, { import React, { createContext, useState, useCallback, useMemo, useRef, useEffect } from 'react';
createContext,
useState,
useCallback,
useMemo,
useRef,
useEffect,
} from 'react';
import { useRecoilValue } from 'recoil'; import { useRecoilValue } from 'recoil';
import { useSettings } from '../../../apps/settings/hooks/useSettings'; import { useSettings } from '../../../apps/settings/hooks/useSettings';
import { phoneState } from '../../phone/hooks/state'; import { phoneState } from '../../phone/hooks/state';
@@ -53,11 +46,7 @@ export const NotificationsContext = createContext<{
updateId(id: string, value: Partial<INotification>): void; updateId(id: string, value: Partial<INotification>): void;
removeId(id: string): void; removeId(id: string): void;
hasNotification(app: string): number; hasNotification(app: string): number;
addNotificationAlert( addNotificationAlert(n: INotification, persist: boolean, update?: Partial<INotification>);
n: INotification,
persist: boolean,
update?: Partial<INotification>,
);
}>(null); }>(null);
export function NotificationsProvider({ children }) { export function NotificationsProvider({ children }) {
@@ -72,9 +61,7 @@ export function NotificationsProvider({ children }) {
const { mount, play } = useSoundProvider(); const { mount, play } = useSoundProvider();
const alertTimeout = useRef<NodeJS.Timeout>(); const alertTimeout = useRef<NodeJS.Timeout>();
const [alerts, setAlerts] = useState< const [alerts, setAlerts] = useState<Array<[INotification, boolean, Partial<INotification>, string | undefined]>>([]);
Array<[INotification, boolean, Partial<INotification>, string | undefined]>
>([]);
const [currentAlert, setCurrentAlert] = useState<INotificationAlert>(); const [currentAlert, setCurrentAlert] = useState<INotificationAlert>();
useEffect(() => { useEffect(() => {
@@ -127,12 +114,7 @@ export function NotificationsProvider({ children }) {
); );
const _showAlert = useCallback( const _showAlert = useCallback(
( (n: INotification, persist: boolean, update: Partial<INotification>, soundUrl: string) => {
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) {
@@ -172,16 +154,10 @@ export function NotificationsProvider({ children }) {
[addOrUpdateNotification, play], [addOrUpdateNotification, play],
); );
const addNotificationAlert = ( const addNotificationAlert = (n: INotification, persist?: boolean, update?: Partial<INotification>) => {
n: INotification,
persist?: boolean,
update?: Partial<INotification>,
) => {
if (n.sound) { if (n.sound) {
const { sound, volume } = getSoundSettings('notification', settings, n.app); const { sound, volume } = getSoundSettings('notification', settings, n.app);
mount(sound, volume, false).then(({ url }) => mount(sound, volume, false).then(({ url }) => setAlerts((curr) => [...curr, [n, persist, update, url]]));
setAlerts((curr) => [...curr, [n, persist, update, url]]),
);
return; return;
} }
setAlerts((curr) => [...curr, [n, persist, update, undefined]]); setAlerts((curr) => [...curr, [n, persist, update, undefined]]);
+2 -24
View File
@@ -21,16 +21,7 @@ const useSound = (url: string, options: ISoundOptions = DEFAULT_OPTIONS) => {
const [isPlaying, setPlaying] = useState<boolean>(false); const [isPlaying, setPlaying] = useState<boolean>(false);
const { const { mount, play, stop, playing, volume, loop, remove, isMounted } = useSoundProvider();
mount,
play,
stop,
playing,
volume,
loop,
remove,
isMounted,
} = useSoundProvider();
const previousInterrupt = usePreviousState(interrupt); const previousInterrupt = usePreviousState(interrupt);
const previousUrl = usePreviousState(url); const previousUrl = usePreviousState(url);
@@ -50,20 +41,7 @@ const useSound = (url: string, options: ISoundOptions = DEFAULT_OPTIONS) => {
} }
volume(url, vol); volume(url, vol);
loop(url, isLoop); loop(url, isLoop);
}, [ }, [url, vol, isLoop, isMounted, volume, loop, mount, previousUrl, stop, remove, isPlaying, play]);
url,
vol,
isLoop,
isMounted,
volume,
loop,
mount,
previousUrl,
stop,
remove,
isPlaying,
play,
]);
useEffect(() => { useEffect(() => {
if (interrupt) { if (interrupt) {
+40 -55
View File
@@ -7,12 +7,7 @@ interface IMountResponse {
} }
interface ISoundContext { interface ISoundContext {
mount( mount(url: string, volume?: number, loop?: boolean, autoplay?: boolean): Promise<IMountResponse>;
url: string,
volume?: number,
loop?: boolean,
autoplay?: boolean,
): Promise<IMountResponse>;
play(url?: string, volume?: number, loop?: boolean): void; play(url?: string, volume?: number, loop?: boolean): void;
stop(url: string): void; stop(url: string): void;
remove(url: string): boolean; remove(url: string): boolean;
@@ -31,55 +26,47 @@ export const SoundProvider = ({ children }: { children: React.ReactNode }) => {
soundRefs.current = new Map(); soundRefs.current = new Map();
}, []); }, []);
const mount = useCallback( const mount = useCallback((url: string, volume: number = 1, loop: boolean = false, autoplay: boolean = false) => {
( return new Promise<IMountResponse>((res) => {
url: string, if (!soundRefs.current) {
volume: number = 1, soundRefs.current = new Map();
loop: boolean = false, }
autoplay: boolean = false,
) => { const find = soundRefs.current.get(url);
return new Promise<IMountResponse>((res) => {
if (!soundRefs.current) { if (find) {
soundRefs.current = new Map(); find.howl.volume(volume);
find.howl.loop(loop);
if (autoplay) {
find.howl.play();
} }
return res({ howl: find.howl, url });
}
const find = soundRefs.current.get(url); const instance = new Howl({
src: url,
if (find) { loop,
find.howl.volume(volume); volume,
find.howl.loop(loop); autoplay,
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);
}); });
},
[], 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( const play = useCallback(
(url: string, volume: number, loop: boolean) => { (url: string, volume: number, loop: boolean) => {
@@ -167,9 +154,7 @@ export const SoundProvider = ({ children }: { children: React.ReactNode }) => {
}, []); }, []);
return ( return (
<soundContext.Provider <soundContext.Provider value={{ mount, play, stop, playing, remove, volume, loop, isMounted }}>
value={{ mount, play, stop, playing, remove, volume, loop, isMounted }}
>
{children} {children}
</soundContext.Provider> </soundContext.Provider>
); );
+2 -9
View File
@@ -1,8 +1,5 @@
import { IPhoneSettings } from '../../../apps/settings/hooks/useSettings'; import { IPhoneSettings } from '../../../apps/settings/hooks/useSettings';
import { import { getNotificationPath, getRingtonePath } from '../../../apps/settings/utils/getRingtonePath';
getNotificationPath,
getRingtonePath,
} from '../../../apps/settings/utils/getRingtonePath';
const getPath = { const getPath = {
ringtone: getRingtonePath, ringtone: getRingtonePath,
@@ -12,11 +9,7 @@ const getPath = {
/** /**
* Gets the configuration for SoundProvider based on settings and apps * Gets the configuration for SoundProvider based on settings and apps
*/ */
export const getSoundSettings = ( export const getSoundSettings = (type: 'ringtone' | 'notification', settings: IPhoneSettings, app?: string) => {
type: 'ringtone' | 'notification',
settings: IPhoneSettings,
app?: string,
) => {
try { try {
return app return app
? { ? {
+2 -12
View File
@@ -23,23 +23,13 @@ const useStyles = makeStyles(() => ({
}, },
})); }));
export const AppContent = ({ export const AppContent = ({ children, style, backdrop, onClickBackdrop, ...props }: AppContentTypes & BoxProps) => {
children,
style,
backdrop,
onClickBackdrop,
...props
}: AppContentTypes & BoxProps) => {
const classes = useStyles(); const classes = useStyles();
return ( return (
<Paper className={classes.wrapper} square> <Paper className={classes.wrapper} square>
<Box flexGrow={1} className={classes.box} {...props}> <Box flexGrow={1} className={classes.box} {...props}>
<Paper square elevation={0} className={classes.paper}> <Paper square elevation={0} className={classes.paper}>
<Backdrop <Backdrop className={classes.backdrop} open={backdrop || false} onClick={onClickBackdrop} />
className={classes.backdrop}
open={backdrop || false}
onClick={onClickBackdrop}
/>
{children} {children}
</Paper> </Paper>
</Box> </Box>
+21 -35
View File
@@ -5,38 +5,28 @@ 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';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
const useStyles = makeStyles<Theme, { color: string; backgroundColor: string }>( const useStyles = makeStyles<Theme, { color: string; backgroundColor: string }>((theme) => ({
(theme) => ({ root: {
root: { padding: 0,
padding: 0, marginTop: theme.spacing(3),
marginTop: theme.spacing(3), },
avatar: {
'&:hover': {
backgroundColor: ({ backgroundColor }) => darken(backgroundColor, 0.1),
}, },
avatar: { backgroundColor: ({ backgroundColor }) => backgroundColor,
'&:hover': { color: ({ color }) => color,
backgroundColor: ({ backgroundColor }) => darken(backgroundColor, 0.1), boxShadow: theme.shadows[2],
}, width: theme.spacing(8),
backgroundColor: ({ backgroundColor }) => backgroundColor, height: theme.spacing(8),
color: ({ color }) => color, fontSize: theme.typography.h4.fontSize,
boxShadow: theme.shadows[2], },
width: theme.spacing(8), tooltip: {
height: theme.spacing(8), fontSize: 12,
fontSize: theme.typography.h4.fontSize, },
}, }));
tooltip: {
fontSize: 12,
},
}),
);
export const AppIcon = ({ export const AppIcon = ({ id, nameLocale, name, icon, backgroundColor, color, notification }) => {
id,
nameLocale,
name,
icon,
backgroundColor,
color,
notification,
}) => {
const { t } = useTranslation(); const { t } = useTranslation();
const classes = useStyles({ const classes = useStyles({
backgroundColor: backgroundColor || green[50], backgroundColor: backgroundColor || green[50],
@@ -53,11 +43,7 @@ export const AppIcon = ({
TransitionComponent={Zoom} TransitionComponent={Zoom}
> >
<Button className={classes.root}> <Button className={classes.root}>
<Badge <Badge color="error" badgeContent={notification?.badge} invisible={!notification || notification.badge < 2}>
color="error"
badgeContent={notification?.badge}
invisible={!notification || notification.badge < 2}
>
<Avatar className={classes.avatar}>{icon || name[0].toUpperCase()}</Avatar> <Avatar className={classes.avatar}>{icon || name[0].toUpperCase()}</Avatar>
</Badge> </Badge>
</Button> </Button>
+1 -5
View File
@@ -28,11 +28,7 @@ const useStyle = makeStyles(
); );
// Taso: Maybe we should pass an icon (maybe fa?) as a prop as well at somepoint // Taso: Maybe we should pass an icon (maybe fa?) as a prop as well at somepoint
// but need to think about the best way to do that for standardization sake. // but need to think about the best way to do that for standardization sake.
export const AppTitle = ({ export const AppTitle = ({ app: { backgroundColor, color, nameLocale }, variant = 'h5', ...props }: IProps) => {
app: { backgroundColor, color, nameLocale },
variant = 'h5',
...props
}: IProps) => {
const classes = useStyle({ color, backgroundColor }); const classes = useStyle({ color, backgroundColor });
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
+1 -6
View File
@@ -1,12 +1,7 @@
import React from 'react'; import React from 'react';
import { AppWrapperTypes } from '../interface/InterfaceUI'; import { AppWrapperTypes } from '../interface/InterfaceUI';
export const AppWrapper = ({ export const AppWrapper = ({ children, style, handleClickAway, ...props }: AppWrapperTypes) => {
children,
style,
handleClickAway,
...props
}: AppWrapperTypes) => {
return ( return (
<div <div
{...props} {...props}
+4 -13
View File
@@ -17,11 +17,9 @@ const useStyles = makeStyles(
}, },
}, },
outlined: { outlined: {
border: ({ color }: IStatusButtonStyleProps) => border: ({ color }: IStatusButtonStyleProps) => `1px solid ${fade(theme.palette[color].main, 0.5)}`,
`1px solid ${fade(theme.palette[color].main, 0.5)}`,
'&:hover': { '&:hover': {
border: ({ color }: IStatusButtonStyleProps) => border: ({ color }: IStatusButtonStyleProps) => `1px solid ${theme.palette[color].main}`,
`1px solid ${theme.palette[color].main}`,
}, },
'&$disabled': { '&$disabled': {
border: `1px solid ${theme.palette.action.disabled}`, border: `1px solid ${theme.palette.action.disabled}`,
@@ -31,8 +29,7 @@ const useStyles = makeStyles(
color: ({ color }: IStatusButtonStyleProps) => theme.palette[color].contrastText, color: ({ color }: IStatusButtonStyleProps) => theme.palette[color].contrastText,
backgroundColor: ({ color }: IStatusButtonStyleProps) => theme.palette[color].main, backgroundColor: ({ color }: IStatusButtonStyleProps) => theme.palette[color].main,
'&:hover': { '&:hover': {
backgroundColor: ({ color }: IStatusButtonStyleProps) => backgroundColor: ({ color }: IStatusButtonStyleProps) => theme.palette[color].dark,
theme.palette[color].dark,
}, },
}, },
}), }),
@@ -46,11 +43,5 @@ export const StatusButton = ({
...props ...props
}: Omit<ButtonProps, 'color'> & { color: StatusButtonStyleColor }) => { }: Omit<ButtonProps, 'color'> & { color: StatusButtonStyleColor }) => {
const classes = useStyles({ color }); const classes = useStyles({ color });
return ( return <Button variant={variant} className={`${classes.root} ${classes[variant] || ''} ${className}`} {...props} />;
<Button
variant={variant}
className={`${classes.root} ${classes[variant] || ''} ${className}`}
{...props}
/>
);
}; };
+4 -8
View File
@@ -13,16 +13,13 @@ const useStyles = makeStyles(
color: ({ color }: IStatusButtonStyleProps) => theme.palette[color].contrastText, color: ({ color }: IStatusButtonStyleProps) => theme.palette[color].contrastText,
backgroundColor: ({ color }: IStatusButtonStyleProps) => theme.palette[color].main, backgroundColor: ({ color }: IStatusButtonStyleProps) => theme.palette[color].main,
'&:hover': { '&:hover': {
backgroundColor: ({ color }: IStatusButtonStyleProps) => backgroundColor: ({ color }: IStatusButtonStyleProps) => theme.palette[color].light,
theme.palette[color].light,
}, },
}, },
outlined: { outlined: {
border: ({ color }: IStatusButtonStyleProps) => border: ({ color }: IStatusButtonStyleProps) => `1px solid ${fade(theme.palette[color].main, 0.5)}`,
`1px solid ${fade(theme.palette[color].main, 0.5)}`,
'&:hover': { '&:hover': {
border: ({ color }: IStatusButtonStyleProps) => border: ({ color }: IStatusButtonStyleProps) => `1px solid ${theme.palette[color].main}`,
`1px solid ${theme.palette[color].main}`,
}, },
'&$disabled': { '&$disabled': {
border: `1px solid ${theme.palette.action.disabled}`, border: `1px solid ${theme.palette.action.disabled}`,
@@ -32,8 +29,7 @@ const useStyles = makeStyles(
color: ({ color }: IStatusButtonStyleProps) => theme.palette[color].contrastText, color: ({ color }: IStatusButtonStyleProps) => theme.palette[color].contrastText,
backgroundColor: ({ color }: IStatusButtonStyleProps) => theme.palette[color].main, backgroundColor: ({ color }: IStatusButtonStyleProps) => theme.palette[color].main,
'&:hover': { '&:hover': {
backgroundColor: ({ color }: IStatusButtonStyleProps) => backgroundColor: ({ color }: IStatusButtonStyleProps) => theme.palette[color].dark,
theme.palette[color].dark,
}, },
}, },
}), }),
+1 -6
View File
@@ -23,10 +23,5 @@ export const useContextMenu = (_options?): UseContextMenu => {
setOpen(true); setOpen(true);
}; };
return [ return [onOpen, onClose, () => <ContextMenu open={open} onClose={onClose} options={options} />, open];
onOpen,
onClose,
() => <ContextMenu open={open} onClose={onClose} options={options} />,
open,
];
}; };
+1 -5
View File
@@ -16,11 +16,7 @@ function SnackbarProvider({ children }) {
return () => clearTimeout(timer.current); return () => clearTimeout(timer.current);
}, [alert]); }, [alert]);
return ( return <SnackbarContext.Provider value={{ alert, addAlert: setAlert }}>{children}</SnackbarContext.Provider>;
<SnackbarContext.Provider value={{ alert, addAlert: setAlert }}>
{children}
</SnackbarContext.Provider>
);
} }
export default SnackbarProvider; export default SnackbarProvider;
+1 -4
View File
@@ -1,6 +1,3 @@
module.exports = { module.exports = {
presets: [ presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'],
['@babel/preset-env', { targets: { node: 'current' } }],
'@babel/preset-typescript',
],
}; };
+33 -39
View File
@@ -11,26 +11,23 @@ on(`__cfx_nui:${events.PHONE_INITIALIZE_CALL}`, (data: any, cb: Function) => {
cb(); cb();
}); });
onNet( onNet(events.PHONE_START_CALL, (transmitter: string, receiver: string, isTransmitter: boolean) => {
events.PHONE_START_CALL, openCallModal(true);
(transmitter: string, receiver: string, isTransmitter: boolean) => {
openCallModal(true);
SendNuiMessage( SendNuiMessage(
JSON.stringify({ JSON.stringify({
app: 'CALL', app: 'CALL',
method: 'setCaller', method: 'setCaller',
data: { data: {
active: true, active: true,
transmitter: transmitter, transmitter: transmitter,
receiver: receiver, receiver: receiver,
isTransmitter: isTransmitter, isTransmitter: isTransmitter,
accepted: false, accepted: false,
}, },
}), }),
); );
}, });
);
RegisterNuiCallbackType(events.PHONE_ACCEPT_CALL); // Fires when the TARGET accepts. RegisterNuiCallbackType(events.PHONE_ACCEPT_CALL); // Fires when the TARGET accepts.
on(`__cfx_nui:${events.PHONE_ACCEPT_CALL}`, (data: any, cb: Function) => { on(`__cfx_nui:${events.PHONE_ACCEPT_CALL}`, (data: any, cb: Function) => {
@@ -38,26 +35,23 @@ on(`__cfx_nui:${events.PHONE_ACCEPT_CALL}`, (data: any, cb: Function) => {
cb(); cb();
}); });
onNet( onNet(events.PHONE_CALL_WAS_ACCEPTED, (channelId: number, currentCall: ICall, isTransmitter: boolean) => {
events.PHONE_CALL_WAS_ACCEPTED, exp['mumble-voip'].SetCallChannel(channelId);
(channelId: number, currentCall: ICall, isTransmitter: boolean) => { phoneCallStartAnim(); // Trigger call animation only if the call was accepted.
exp['mumble-voip'].SetCallChannel(channelId); SendNuiMessage(
phoneCallStartAnim(); // Trigger call animation only if the call was accepted. JSON.stringify({
SendNuiMessage( app: 'CALL',
JSON.stringify({ method: 'setCaller',
app: 'CALL', data: {
method: 'setCaller', active: true,
data: { transmitter: currentCall.transmitter,
active: true, receiver: currentCall.receiver,
transmitter: currentCall.transmitter, isTransmitter: isTransmitter,
receiver: currentCall.receiver, accepted: true,
isTransmitter: isTransmitter, },
accepted: true, }),
}, );
}), });
);
},
);
RegisterNuiCallbackType(events.PHONE_CALL_REJECTED); // Fires when cancelling and rejecting a call. RegisterNuiCallbackType(events.PHONE_CALL_REJECTED); // Fires when cancelling and rejecting a call.
on(`__cfx_nui:${events.PHONE_CALL_REJECTED}`, (data: any, cb: Function) => { on(`__cfx_nui:${events.PHONE_CALL_REJECTED}`, (data: any, cb: Function) => {
+12 -21
View File
@@ -10,13 +10,10 @@ on(`__cfx_nui:${events.MESSAGES_FETCH_MESSAGE_GROUPS}`, (): void => {
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS); emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS);
}); });
onNet( onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS, (messageGroups: MessageGroup[]): void => {
events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS, sendMessageEvent(events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS, messageGroups);
(messageGroups: MessageGroup[]): void => { emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS);
sendMessageEvent(events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS, messageGroups); });
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS);
},
);
onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED, () => { onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED, () => {
sendMessageEvent(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED); sendMessageEvent(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED);
@@ -26,13 +23,10 @@ onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED, () => {
* Messages create message group * Messages create message group
*/ */
RegisterNuiCallbackType(events.MESSAGES_CREATE_MESSAGE_GROUP); RegisterNuiCallbackType(events.MESSAGES_CREATE_MESSAGE_GROUP);
on( on(`__cfx_nui:${events.MESSAGES_CREATE_MESSAGE_GROUP}`, ({ phoneNumbers, label }: any, cb: Function): void => {
`__cfx_nui:${events.MESSAGES_CREATE_MESSAGE_GROUP}`, emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP, phoneNumbers, label);
({ phoneNumbers, label }: any, cb: Function): void => { cb();
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP, phoneNumbers, label); });
cb();
},
);
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, (result: any): void => { onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, (result: any): void => {
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, result); sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, result);
@@ -47,13 +41,10 @@ onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, (result: any): void => {
* Messages fetch messages * Messages fetch messages
*/ */
RegisterNuiCallbackType(events.MESSAGES_FETCH_MESSAGES); RegisterNuiCallbackType(events.MESSAGES_FETCH_MESSAGES);
on( on(`__cfx_nui:${events.MESSAGES_FETCH_MESSAGES}`, ({ groupId }: any, cb: Function): void => {
`__cfx_nui:${events.MESSAGES_FETCH_MESSAGES}`, emitNet(events.MESSAGES_FETCH_MESSAGES, groupId);
({ groupId }: any, cb: Function): void => { cb();
emitNet(events.MESSAGES_FETCH_MESSAGES, groupId); });
cb();
},
);
onNet(events.MESSAGES_FETCH_MESSAGES_SUCCESS, (messages: Message[]): void => { onNet(events.MESSAGES_FETCH_MESSAGES_SUCCESS, (messages: Message[]): void => {
sendMessageEvent(events.MESSAGES_FETCH_MESSAGES_SUCCESS, messages); sendMessageEvent(events.MESSAGES_FETCH_MESSAGES_SUCCESS, messages);
+3 -43
View File
@@ -24,23 +24,7 @@ const newPhoneProp = async () => {
prop = CreateObject(GetHashKey(phoneModel), x, y, z + 0.2, true, true, true); prop = CreateObject(GetHashKey(phoneModel), x, y, z + 0.2, true, true, true);
//prop = CreateObject(GetHashKey(phoneModel), 1.0, 1.0, 1.0, 1, 1, 0) //prop = CreateObject(GetHashKey(phoneModel), 1.0, 1.0, 1.0, 1, 1, 0)
const boneIndex = GetPedBoneIndex(playerPed, 28422); const boneIndex = GetPedBoneIndex(playerPed, 28422);
AttachEntityToEntity( AttachEntityToEntity(prop, playerPed, boneIndex, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, true, true, false, true, 1.0, true); //-- Attaches the phone to the player.
prop,
playerPed,
boneIndex,
0.0,
0.0,
0.0,
0.0,
0.0,
-0.0,
true,
true,
false,
true,
1.0,
true,
); //-- Attaches the phone to the player.
propCreated = true; propCreated = true;
} else if (propCreated) { } else if (propCreated) {
console.log('prop already created'); console.log('prop already created');
@@ -77,19 +61,7 @@ const handleOpenVehicleAnim = async (playerPed: number): Promise<void> => {
SetCurrentPedWeapon(playerPed, 0xa2719263, true); SetCurrentPedWeapon(playerPed, 0xa2719263, true);
ClearPedTasks(playerPed); ClearPedTasks(playerPed);
await loadAnimDict(dict); await loadAnimDict(dict);
TaskPlayAnim( TaskPlayAnim(playerPed, dict, 'cellphone_text_in', 7.0, -1, -1, 50, 0, false, false, false);
playerPed,
dict,
'cellphone_text_in',
7.0,
-1,
-1,
50,
0,
false,
false,
false,
);
await Delay(300); await Delay(300);
await newPhoneProp(); await newPhoneProp();
}; };
@@ -101,19 +73,7 @@ const handleOpenNormalAnim = async (playerPed: number): Promise<void> => {
SetCurrentPedWeapon(playerPed, 0xa2719263, true); SetCurrentPedWeapon(playerPed, 0xa2719263, true);
ClearPedTasks(playerPed); ClearPedTasks(playerPed);
await loadAnimDict(dict); await loadAnimDict(dict);
TaskPlayAnim( TaskPlayAnim(playerPed, dict, 'cellphone_text_in', 8.0, -1, -1, 50, 0, false, false, false);
playerPed,
dict,
'cellphone_text_in',
8.0,
-1,
-1,
50,
0,
false,
false,
false,
);
await Delay(300); await Delay(300);
await newPhoneProp(); await newPhoneProp();
}; };
+1 -3
View File
@@ -13,9 +13,7 @@ import { mainLogger } from './sv_logger';
// we require set mysql_connection_string to be set in the config // we require set mysql_connection_string to be set in the config
const mysqlConnectionString = GetConvar(CONNECTION_STRING, 'none'); const mysqlConnectionString = GetConvar(CONNECTION_STRING, 'none');
if (mysqlConnectionString === 'none') { if (mysqlConnectionString === 'none') {
const error = new Error( const error = new Error(`No connection string provided. make sure "${CONNECTION_STRING}" is set in your config.`);
`No connection string provided. make sure "${CONNECTION_STRING}" is set in your config.`,
);
mainLogger.error(error.message); mainLogger.error(error.message);
throw error; throw error;
} }
+1 -3
View File
@@ -14,9 +14,7 @@ interface Map {
export function parseSemiColonFormat(connectionString: string): Map { export function parseSemiColonFormat(connectionString: string): Map {
const parts = connectionString.split(';'); const parts = connectionString.split(';');
if (parts.length === 1) { if (parts.length === 1) {
throw new Error( throw new Error(`Connection string ${connectionString} is in the incorrect format. Please follow the README.`);
`Connection string ${connectionString} is in the incorrect format. Please follow the README.`,
);
} }
return parts.reduce((connectionInfo: Map, part) => { return parts.reduce((connectionInfo: Map, part) => {
+1 -4
View File
@@ -15,10 +15,7 @@ const DISCORD_HEADERS = { authorization: `Bot ${DISCORD_TOKEN}` };
const BASE_URL = 'https://discord.com/api'; const BASE_URL = 'https://discord.com/api';
const POST_CHANNEL_URL = `${BASE_URL}/channels/${DISCORD_CHANNEL_ID}/messages`; const POST_CHANNEL_URL = `${BASE_URL}/channels/${DISCORD_CHANNEL_ID}/messages`;
export async function reportTweetToDiscord( export async function reportTweetToDiscord(tweet: Tweet, reportingProfile: Profile): Promise<any> {
tweet: Tweet,
reportingProfile: Profile,
): Promise<any> {
if (!DISCORD_TOKEN || !DISCORD_CHANNEL_ID) { if (!DISCORD_TOKEN || !DISCORD_CHANNEL_ID) {
discordLogger.warn(`Got a request to report a tweet but discord is not discordLogger.warn(`Got a request to report a tweet but discord is not
configured. See README on how to configure discord endpoints.`); configured. See README on how to configure discord endpoints.`);
+1 -3
View File
@@ -13,9 +13,7 @@ async function fetchAllTransactions(identifier: string): Promise<Transfer[]> {
const [results] = await pool.query(query, [identifier]); const [results] = await pool.query(query, [identifier]);
const transactions = <Transfer[]>results; const transactions = <Transfer[]>results;
bankLogger.verbose( bankLogger.verbose(`Fetched all transactions (${identifier}) - ${JSON.stringify(transactions)}`);
`Fetched all transactions (${identifier}) - ${JSON.stringify(transactions)}`,
);
return transactions; return transactions;
} }
+20 -42
View File
@@ -1,11 +1,6 @@
import { ESX } from './server'; import { ESX } from './server';
import events from '../utils/events'; import events from '../utils/events';
import { import { getIdentifierByPhoneNumber, usePhoneNumber, getIdentifier, getSource } from './functions';
getIdentifierByPhoneNumber,
usePhoneNumber,
getIdentifier,
getSource,
} from './functions';
import { XPlayer } from 'esx.js/@types/server'; import { XPlayer } from 'esx.js/@types/server';
import { ICall } from '../../phone/src/common/typings/call'; import { ICall } from '../../phone/src/common/typings/call';
@@ -35,8 +30,7 @@ async function getPlayerFromIdentifier(identifier: string): Promise<XPlayer> {
} }
async function saveCall(call: ICall) { async function saveCall(call: ICall) {
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]);
} }
@@ -46,8 +40,7 @@ async function updateCall(call: ICall, isAccepted: boolean, end: number) {
} }
async function fetchCalls(phoneNumber: string): Promise<ICall[]> { async function fetchCalls(phoneNumber: string): Promise<ICall[]> {
const query = const query = 'SELECT * FROM npwd_calls WHERE receiver = ? OR transmitter = ? ORDER BY id DESC';
'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 = <ICall[]>result;
return calls; return calls;
@@ -87,13 +80,7 @@ onNet(events.PHONE_INITIALIZE_CALL, async (phoneNumber: string, timestamp: numbe
emitNet(events.PHONE_START_CALL, _source, transmitterNumber, receiverNumber, true); emitNet(events.PHONE_START_CALL, _source, transmitterNumber, receiverNumber, true);
// client that is being called // client that is being called
emitNet( emitNet(events.PHONE_START_CALL, xReceiver.source, transmitterNumber, receiverNumber, false);
events.PHONE_START_CALL,
xReceiver.source,
transmitterNumber,
receiverNumber,
false,
);
}); });
onNet(events.PHONE_ACCEPT_CALL, async (transmitterNumber: string) => { onNet(events.PHONE_ACCEPT_CALL, async (transmitterNumber: string) => {
@@ -108,13 +95,7 @@ onNet(events.PHONE_ACCEPT_CALL, async (transmitterNumber: string) => {
emitNet(events.PHONE_CALL_WAS_ACCEPTED, pSource, channelId, currentCall, false); emitNet(events.PHONE_CALL_WAS_ACCEPTED, pSource, channelId, currentCall, false);
// player who is calling // player who is calling
emitNet( emitNet(events.PHONE_CALL_WAS_ACCEPTED, currentCall.transmitterSource, channelId, currentCall, true);
events.PHONE_CALL_WAS_ACCEPTED,
currentCall.transmitterSource,
channelId,
currentCall,
true,
);
currentCall.accepted = true; currentCall.accepted = true;
} catch (e) { } catch (e) {
@@ -124,25 +105,22 @@ onNet(events.PHONE_ACCEPT_CALL, async (transmitterNumber: string) => {
} }
}); });
onNet( onNet(events.PHONE_CALL_REJECTED, async (transmitterNumber: string, timestamp: number) => {
events.PHONE_CALL_REJECTED, const pSource = getSource();
async (transmitterNumber: string, timestamp: number) => { try {
const pSource = getSource(); const currentCall = calls.get(transmitterNumber);
try { await updateCall(currentCall, false, timestamp);
const currentCall = calls.get(transmitterNumber);
await updateCall(currentCall, false, timestamp);
// player who is called and initiasted the rejection. // player who is called and initiasted the rejection.
emitNet(events.PHONE_CALL_WAS_REJECTED, currentCall.receiverSource); emitNet(events.PHONE_CALL_WAS_REJECTED, currentCall.receiverSource);
// player who is calling and recieved the rejection. // player who is calling and recieved the rejection.
emitNet(events.PHONE_CALL_WAS_REJECTED, currentCall.transmitterSource); emitNet(events.PHONE_CALL_WAS_REJECTED, currentCall.transmitterSource);
} catch (e) { } catch (e) {
callLogger.error(`Phone Call Rejected Event Error ${e.message}`, { callLogger.error(`Phone Call Rejected Event Error ${e.message}`, {
source: pSource, source: pSource,
}); });
} }
}, });
);
onNet(events.PHONE_END_CALL, async (transmitterNumber: string, timestamp: number) => { onNet(events.PHONE_END_CALL, async (transmitterNumber: string, timestamp: number) => {
const pSource = getSource(); const pSource = getSource();
+25 -42
View File
@@ -18,35 +18,21 @@ interface ContactId {
} }
async function fetchAllContacts(identifier: string): Promise<Contacts[]> { async function fetchAllContacts(identifier: string): Promise<Contacts[]> {
const query = const query = 'SELECT * FROM npwd_phone_contacts WHERE identifier = ? ORDER BY display ASC';
'SELECT * FROM npwd_phone_contacts WHERE identifier = ? ORDER BY display ASC';
const [results] = await pool.query(query, [identifier]); const [results] = await pool.query(query, [identifier]);
const contacts = <Contacts[]>results; const contacts = <Contacts[]>results;
return contacts; return contacts;
} }
async function addContact( async function addContact(identifier: string, number: string, display: string, avatar: string): Promise<any> {
identifier: string, const query = 'INSERT INTO npwd_phone_contacts (identifier, number, display, avatar) VALUES (?, ?, ?, ?)';
number: string,
display: string,
avatar: string,
): Promise<any> {
const query =
'INSERT INTO npwd_phone_contacts (identifier, number, display, avatar) VALUES (?, ?, ?, ?)';
const [result] = await pool.query(query, [identifier, number, display, avatar]); const [result] = await pool.query(query, [identifier, number, display, avatar]);
} }
async function updateContact(contact: Contacts, identifier: string): Promise<any> { async function updateContact(contact: Contacts, identifier: string): Promise<any> {
const query = const query = 'UPDATE npwd_phone_contacts SET number = ?, display = ?, avatar = ? WHERE id = ? AND identifier = ?';
'UPDATE npwd_phone_contacts SET number = ?, display = ?, avatar = ? WHERE id = ? AND identifier = ?'; await pool.query(query, [contact.number, contact.display, contact.avatar, contact.id, identifier]);
await pool.query(query, [
contact.number,
contact.display,
contact.avatar,
contact.id,
identifier,
]);
} }
async function deleteContact(contact: ContactId, identifier: string): Promise<any> { async function deleteContact(contact: ContactId, identifier: string): Promise<any> {
@@ -66,29 +52,26 @@ onNet(events.CONTACTS_GET_CONTACTS, async () => {
} }
}); });
onNet( onNet(events.CONTACTS_ADD_CONTACT, async (number: string, display: string, avatar: string) => {
events.CONTACTS_ADD_CONTACT, const _source = getSource();
async (number: string, display: string, avatar: string) => { try {
const _source = getSource(); const _identifier = getIdentifier(_source);
try { await addContact(_identifier, number, display, avatar);
const _identifier = getIdentifier(_source); emitNet(events.CONTACTS_ADD_CONTACT_SUCCESS, _source);
await addContact(_identifier, number, display, avatar); emitNet(events.CONTACTS_ACTION_RESULT, _source, {
emitNet(events.CONTACTS_ADD_CONTACT_SUCCESS, _source); message: 'CONTACT_ADD_SUCCESS',
emitNet(events.CONTACTS_ACTION_RESULT, _source, { type: 'success',
message: 'CONTACT_ADD_SUCCESS', });
type: 'success', } catch (e) {
}); emitNet(events.CONTACTS_ACTION_RESULT, _source, {
} catch (e) { message: 'CONTACT_ADD_FAILED',
emitNet(events.CONTACTS_ACTION_RESULT, _source, { type: 'error',
message: 'CONTACT_ADD_FAILED', });
type: 'error', contactsLogger.error(`Failed to add contact, ${e.message}`, {
}); source: _source,
contactsLogger.error(`Failed to add contact, ${e.message}`, { });
source: _source, }
}); });
}
},
);
onNet(events.CONTACTS_UPDATE_CONTACT, async (contact: Contacts) => { onNet(events.CONTACTS_UPDATE_CONTACT, async (contact: Contacts) => {
const _source = getSource(); const _source = getSource();
+2 -4
View File
@@ -7,14 +7,12 @@ const manualColorize = (strToColor: string): string => `[\x1b[35m${strToColor}\x
// Format handler passed to winston // Format handler passed to winston
const formatLogs = (log: winston.Logform.TransformableInfo): string => { const formatLogs = (log: winston.Logform.TransformableInfo): string => {
if (log.module) if (log.module) return `${log.label} ${manualColorize(log.module)} [${log.level}]: ${log.message}`;
return `${log.label} ${manualColorize(log.module)} [${log.level}]: ${log.message}`;
return `${log.label} [${log.level}]: ${log.message}`; return `${log.label} [${log.level}]: ${log.message}`;
}; };
const findLogPath = () => const findLogPath = () => `${path.join(GetResourcePath(GetCurrentResourceName()), 'sv_npwd.log')}`;
`${path.join(GetResourcePath(GetCurrentResourceName()), 'sv_npwd.log')}`;
// Initiate the main logger for NPWD // Initiate the main logger for NPWD
export const mainLogger = winston.createLogger({ export const mainLogger = winston.createLogger({
+1 -6
View File
@@ -1,12 +1,7 @@
import { ESX } from './server'; import { ESX } from './server';
import { pool } from './db'; import { pool } from './db';
import config from '../utils/config'; import config from '../utils/config';
import { import { getIdentifier, getIdentifierByPhoneNumber, getSource, usePhoneNumber } from './functions';
getIdentifier,
getIdentifierByPhoneNumber,
getSource,
usePhoneNumber,
} from './functions';
import { mainLogger } from './sv_logger'; import { mainLogger } from './sv_logger';
//db = DatabaseConfig //helper variable for use in server function //db = DatabaseConfig //helper variable for use in server function
+65 -106
View File
@@ -1,11 +1,7 @@
import md5 from 'md5'; import md5 from 'md5';
import events from '../utils/events'; import events from '../utils/events';
import { import { Message, MessageGroup, CreateMessageGroupResult } from '../../phone/src/common/typings/messages';
Message,
MessageGroup,
CreateMessageGroupResult,
} from '../../phone/src/common/typings/messages';
import { pool, withTransaction } from './db'; import { pool, withTransaction } from './db';
import { getSource, getIdentifier } from './functions'; import { getSource, getIdentifier } from './functions';
import { mainLogger } from './sv_logger'; import { mainLogger } from './sv_logger';
@@ -46,11 +42,7 @@ interface MessageGroupMapping {
* @param groupId - the message group ID to attach this message to * @param groupId - the message group ID to attach this message to
* @param message - content of the message * @param message - content of the message
*/ */
async function createMessage( async function createMessage(userIdentifier: string, groupId: string, message: string): Promise<any> {
userIdentifier: string,
groupId: string,
message: string,
): Promise<any> {
const query = ` const query = `
INSERT INTO npwd_messages INSERT INTO npwd_messages
(user_identifier, message, group_id) (user_identifier, message, group_id)
@@ -65,9 +57,7 @@ async function createMessage(
* populate the list of message groups on the UI * populate the list of message groups on the UI
* @param userIdentifier - identifier of the user to get message groups for * @param userIdentifier - identifier of the user to get message groups for
*/ */
async function getMessageGroups( async function getMessageGroups(userIdentifier: string): Promise<UnformattedMessageGroup[]> {
userIdentifier: string,
): Promise<UnformattedMessageGroup[]> {
const query = ` const query = `
SELECT SELECT
npwd_messages_groups.group_id, npwd_messages_groups.group_id,
@@ -89,11 +79,7 @@ async function getMessageGroups(
WHERE npwd_messages_groups.participant_identifier != ? WHERE npwd_messages_groups.participant_identifier != ?
ORDER BY npwd_messages_groups.createdAt DESC ORDER BY npwd_messages_groups.createdAt DESC
`; `;
const [results] = await pool.query(query, [ const [results] = await pool.query(query, [userIdentifier, userIdentifier, userIdentifier]);
userIdentifier,
userIdentifier,
userIdentifier,
]);
return <UnformattedMessageGroup[]>results; return <UnformattedMessageGroup[]>results;
} }
@@ -136,11 +122,7 @@ async function getMessages(userIdentifier: string, groupId: string): Promise<Mes
* @param groupId - groupId this label is attached to * @param groupId - groupId this label is attached to
* @param label - the label itself * @param label - the label itself
*/ */
async function createLabel( async function createLabel(userIdentifier: string, groupId: string, label: string): Promise<any> {
userIdentifier: string,
groupId: string,
label: string,
): Promise<any> {
const query = ` const query = `
INSERT INTO npwd_messages_labels INSERT INTO npwd_messages_labels
(user_identifier, group_id, label) (user_identifier, group_id, label)
@@ -166,11 +148,7 @@ async function createMessageGroup(
(user_identifier, group_id, participant_identifier) (user_identifier, group_id, participant_identifier)
VALUES (?, ?, ?) VALUES (?, ?, ?)
`; `;
const [results] = await pool.query(query, [ const [results] = await pool.query(query, [userIdentifier, groupId, participantIdentifier]);
userIdentifier,
groupId,
participantIdentifier,
]);
} }
/** /**
@@ -225,36 +203,28 @@ async function getMessageCountByGroup(groupId: string): Promise<number> {
* groups into a single MessageGroup object. * groups into a single MessageGroup object.
* @param userIdentifier - the user identifier to get message groups for * @param userIdentifier - the user identifier to get message groups for
*/ */
async function getConsolidatedMessageGroups( async function getConsolidatedMessageGroups(userIdentifier: string): Promise<MessageGroupMapping> {
userIdentifier: string,
): Promise<MessageGroupMapping> {
const messageGroups = await getMessageGroups(userIdentifier); const messageGroups = await getMessageGroups(userIdentifier);
return messageGroups.reduce( return messageGroups.reduce((mapping: MessageGroupMapping, messageGroup: UnformattedMessageGroup) => {
(mapping: MessageGroupMapping, messageGroup: UnformattedMessageGroup) => { const groupId = messageGroup.group_id;
const groupId = messageGroup.group_id; const displayTerm = messageGroup.display || messageGroup.phone_number || '???';
const displayTerm = messageGroup.display || messageGroup.phone_number || '???';
if (groupId in mapping) { if (groupId in mapping) {
mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm); mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm);
} else { } else {
mapping[groupId] = { mapping[groupId] = {
user_identifier: messageGroup.user_identifier, user_identifier: messageGroup.user_identifier,
avatar: messageGroup.avatar, avatar: messageGroup.avatar,
label: messageGroup.label, label: messageGroup.label,
participants: [displayTerm], participants: [displayTerm],
updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null, updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null,
}; };
} }
return mapping; return mapping;
}, }, {});
{},
);
} }
async function getGroupIds( async function getGroupIds(userIdentifier: string, groupMapping: MessageGroupMapping): Promise<string[]> {
userIdentifier: string,
groupMapping: MessageGroupMapping,
): Promise<string[]> {
const groupIds: string[] = []; const groupIds: string[] = [];
for (const groupId of Object.keys(groupMapping)) { for (const groupId of Object.keys(groupMapping)) {
const isMine = groupMapping[groupId].user_identifier === userIdentifier; const isMine = groupMapping[groupId].user_identifier === userIdentifier;
@@ -270,9 +240,7 @@ async function getGroupIds(
* of MessageGroup objects ready for the UI to consume * of MessageGroup objects ready for the UI to consume
* @param userIdentifier - user to generate the MessageGroups for * @param userIdentifier - user to generate the MessageGroups for
*/ */
async function getFormattedMessageGroups( async function getFormattedMessageGroups(userIdentifier: string): Promise<MessageGroup[]> {
userIdentifier: string,
): Promise<MessageGroup[]> {
const groupMapping = await getConsolidatedMessageGroups(userIdentifier); const groupMapping = await getConsolidatedMessageGroups(userIdentifier);
const groupIds = await getGroupIds(userIdentifier, groupMapping); const groupIds = await getGroupIds(userIdentifier, groupMapping);
@@ -352,9 +320,7 @@ async function createMessageGroupsFromPhoneNumbers(
// create a row that contains ourselves so reverse accessing from // create a row that contains ourselves so reverse accessing from
// other players works as expected // other players works as expected
createMessageGroup(userIdentifier, groupId, userIdentifier), createMessageGroup(userIdentifier, groupId, userIdentifier),
...identifiers.map((identifier) => ...identifiers.map((identifier) => createMessageGroup(userIdentifier, groupId, identifier)),
createMessageGroup(userIdentifier, groupId, identifier),
),
]; ];
// we allow users to attach labels to name their group chats // we allow users to attach labels to name their group chats
@@ -386,60 +352,53 @@ onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, async () => {
} }
}); });
onNet( onNet(events.MESSAGES_CREATE_MESSAGE_GROUP, async (phoneNumbers: string[], label: string = null) => {
events.MESSAGES_CREATE_MESSAGE_GROUP, const _source = getSource();
async (phoneNumbers: string[], label: string = null) => { try {
const _source = getSource(); const _identifier = await getIdentifier(_source);
try { const result = await createMessageGroupsFromPhoneNumbers(_identifier, phoneNumbers, label);
const _identifier = await getIdentifier(_source);
const result = await createMessageGroupsFromPhoneNumbers(
_identifier,
phoneNumbers,
label,
);
if (result.error && result.duplicate) { if (result.error && result.duplicate) {
emitNet(events.MESSAGES_ACTION_RESULT, _source, { emitNet(events.MESSAGES_ACTION_RESULT, _source, {
message: 'MESSAGES_MESSAGE_GROUP_DUPLICATE', message: 'MESSAGES_MESSAGE_GROUP_DUPLICATE',
type: 'error', type: 'error',
}); });
// if the phoneNumber is invalid // if the phoneNumber is invalid
} else if (result.error && result.phoneNumber) { } else if (result.error && result.phoneNumber) {
emitNet(events.MESSAGES_ACTION_RESULT, _source, { emitNet(events.MESSAGES_ACTION_RESULT, _source, {
message: 'MESSAGES_INVALID_PHONE_NUMBER', message: 'MESSAGES_INVALID_PHONE_NUMBER',
type: 'error', type: 'error',
}); });
// if you are try to add yourself
} else if (result.error && result.mine) {
emitNet(events.MESSAGES_ACTION_RESULT, _source, {
message: 'MESSAGES_MESSAGE_GROUP_CREATE_MINE',
type: 'error',
});
} else if (result.error) {
// if it just fails, welp
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, _source, result);
emitNet(events.MESSAGES_ACTION_RESULT, _source, {
message: `MESSAGES_MESSAGE_GROUP_CREATE_FAILED:`,
type: 'error',
});
} else {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, _source, result);
}
} catch (e) {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, _source);
// if you are try to add yourself
} else if (result.error && result.mine) {
emitNet(events.MESSAGES_ACTION_RESULT, _source, {
message: 'MESSAGES_MESSAGE_GROUP_CREATE_MINE',
type: 'error',
});
} else if (result.error) {
// if it just fails, welp
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, _source, result);
emitNet(events.MESSAGES_ACTION_RESULT, _source, { emitNet(events.MESSAGES_ACTION_RESULT, _source, {
message: `MESSAGES_MESSAGE_GROUP_CREATE_FAILED:`, message: `MESSAGES_MESSAGE_GROUP_CREATE_FAILED:`,
type: 'error', type: 'error',
}); });
messageLogger.error(`Failed to create message group, ${e.message}`, { } else {
source: _source, emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, _source, result);
});
} }
}, } catch (e) {
); emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, _source);
emitNet(events.MESSAGES_ACTION_RESULT, _source, {
message: `MESSAGES_MESSAGE_GROUP_CREATE_FAILED:`,
type: 'error',
});
messageLogger.error(`Failed to create message group, ${e.message}`, {
source: _source,
});
}
});
onNet(events.MESSAGES_FETCH_MESSAGES, async (groupId: string) => { onNet(events.MESSAGES_FETCH_MESSAGES, async (groupId: string) => {
const _source = getSource(); const _source = getSource();
+1 -2
View File
@@ -23,8 +23,7 @@ async function deleteNote(noteId: number, identifier: string) {
} }
async function updateNote(note: Note, identifier: string): Promise<any> { async function updateNote(note: Note, identifier: string): Promise<any> {
const query = const query = 'UPDATE npwd_notes SET title = ?, content = ? WHERE id = ? AND identifier = ?';
'UPDATE npwd_notes SET title = ?, content = ? WHERE id = ? AND identifier = ?';
await pool.query(query, [note.title, note.content, note.id, identifier]); await pool.query(query, [note.title, note.content, note.id, identifier]);
} }
+1 -2
View File
@@ -12,8 +12,7 @@ async function uploadPhoto(identifier: string, image: string) {
} }
async function getPhotosByIdentifier(identifier: string): Promise<IPhoto[]> { async function getPhotosByIdentifier(identifier: string): Promise<IPhoto[]> {
const query = const query = 'SELECT id, image FROM npwd_phone_gallery WHERE identifier = ? ORDER BY id DESC';
'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]);
const photos = <IPhoto[]>results; const photos = <IPhoto[]>results;
return photos; return photos;
+2 -14
View File
@@ -17,22 +17,10 @@ async function fetchAllListings(): Promise<MarketplaceListing[]> {
return listings; return listings;
} }
async function addListing( async function addListing(identifier: string, name: string, number: any, listing: MarketplaceListing): Promise<void> {
identifier: string,
name: string,
number: any,
listing: MarketplaceListing,
): Promise<void> {
const query = const query =
'INSERT INTO npwd_sellout_listings (identifier, name, number, title, url, description) VALUES (?, ?, ?, ?, ?, ?)'; 'INSERT INTO npwd_sellout_listings (identifier, name, number, title, url, description) VALUES (?, ?, ?, ?, ?, ?)';
await pool.query(query, [ await pool.query(query, [identifier, name, number, listing.title, listing.url, listing.description]);
identifier,
name,
number,
listing.title,
listing.url,
listing.description,
]);
} }
onNet(events.SELLOUT_FETCH_LISTING, async () => { onNet(events.SELLOUT_FETCH_LISTING, async () => {
+2 -10
View File
@@ -49,10 +49,7 @@ async function fetchAllTweets(profileId: number): Promise<Tweet[]> {
* @param profileId - twitter profile id of the player * @param profileId - twitter profile id of the player
* @param searchValue - value to search * @param searchValue - value to search
*/ */
async function fetchTweetsFiltered( async function fetchTweetsFiltered(profileId: number, searchValue: string): Promise<Tweet[]> {
profileId: number,
searchValue: string,
): Promise<Tweet[]> {
const parameterizedSearchValue = `%${searchValue}%`; const parameterizedSearchValue = `%${searchValue}%`;
const query = ` const query = `
SELECT SELECT
@@ -71,12 +68,7 @@ async function fetchTweetsFiltered(
ORDER BY npwd_twitter_tweets.createdAt DESC ORDER BY npwd_twitter_tweets.createdAt DESC
LIMIT 100 LIMIT 100
`; `;
const [results] = await pool.query(query, [ const [results] = await pool.query(query, [profileId, profileId, parameterizedSearchValue, parameterizedSearchValue]);
profileId,
profileId,
parameterizedSearchValue,
parameterizedSearchValue,
]);
const tweets = <Tweet[]>results; const tweets = <Tweet[]>results;
return tweets.map((tweet) => ({ return tweets.map((tweet) => ({
...tweet, ...tweet,