From c4fca1e793f0fa374d43d0b61f826f0a66536bba Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 12:07:22 +0500 Subject: [PATCH] initial lint --no-verify --- .vscode/settings.json | 3 +- .../actionModal/view/actionModalStyles.ts | 133 +++-- .../assetIcon/styles/assetIcon.styles.ts | 40 +- .../container/writePostButton.tsx | 72 +-- src/components/atoms/writePostButton/index.ts | 2 +- .../basicHeader/view/basicHeaderView.tsx | 4 +- .../view/placeHolder/boostPlaceHolderView.js | 28 +- .../placeHolder/commentPlaceHolderView.js | 4 - .../placeHolder/communitiesPlaceHolder.js | 3 +- .../placeHolder/listItemPlaceHolderView.js | 2 - .../placeHolder/postCardPlaceHolderView.js | 2 +- .../view/placeHolder/postPlaceHolderView.js | 3 +- .../placeHolder/profileSummaryPlaceHolder.js | 1 - .../placeHolder/walletDetailsPlaceHolder.js | 9 +- .../view/userListItem/userListItemStyles.js | 2 - .../walletLineItem/walletLineItemStyles.js | 4 +- .../beneficiaryModal/beneficiaryModal.tsx | 130 ++--- .../beneficiarySelectionContent.tsx | 10 +- .../bottomTabBar/view/bottomTabBarView.tsx | 19 +- src/components/comment/view/commentView.tsx | 9 +- .../comments/container/commentsContainer.tsx | 10 +- src/components/comments/view/commentsView.tsx | 15 +- .../draftListItem/view/draftListItemView.tsx | 2 +- .../titleArea/view/titleAreaView.js | 10 +- .../formInput/view/formInputView.tsx | 4 +- .../header/container/headerContainer.js | 2 - .../insertLinkModal/insertLinkModal.tsx | 8 +- .../children/quickProfileContent.tsx | 474 +++++++++-------- .../children/quickProfileStyles.ts | 170 +++---- .../postCard/children/upvoteButton.tsx | 238 ++++----- .../postComments/children/commentsSection.tsx | 11 +- .../postComments/container/postComments.tsx | 75 ++- .../body/view/commentBodyView.tsx | 1 - .../postHtmlRenderer/postHtmlRenderer.tsx | 5 +- .../postHtmlRendererStyles.ts | 2 +- .../postInteractionHandler.tsx | 445 ++++++++-------- .../postView/view/postDisplayStyles.js | 2 +- .../postView/view/postDisplayView.tsx | 25 +- .../container/postsListContainer.tsx | 8 +- src/components/qrModal/qrModalStyles.ts | 1 + src/components/qrModal/qrModalView.tsx | 16 +- .../quickReplyModalContent.tsx | 195 +++---- .../quickReplyModal/quickReplyModalStyles.ts | 15 +- .../quickReplyModal/quickReplyModalView.tsx | 2 +- .../quickReplyModal/usePostSubmitter.ts | 279 +++++----- .../sideMenu/container/sideMenuContainer.tsx | 37 +- .../snippetEditorModalStyles.ts | 118 +++-- .../snippetsModal/snippetsModalStyles.ts | 43 +- .../tabbedPosts/container/tabbedPosts.tsx | 65 ++- .../tabbedPosts/services/tabbedPostsFetch.ts | 5 +- .../tabbedPosts/view/tabContent.tsx | 60 +-- .../textBoxWithCopy/textBoxWithCopy.tsx | 8 +- src/components/transaction/transactionView.js | 2 +- .../transferAccountSelector.tsx | 1 - .../transferAmountInputSection.tsx | 2 +- .../upvotePopover/container/upvotePopover.tsx | 68 ++- .../votersDisplay/view/votersDisplayView.js | 1 - src/components/wallet/view/walletView.js | 1 - src/components/webViewModal/webViewModal.tsx | 2 +- src/constants/defaultAssets.ts | 9 +- src/constants/options/api.js | 16 +- src/constants/options/points.js | 4 +- src/constants/postTypes.ts | 2 +- src/constants/routeNames.js | 1 - src/containers/profileContainer.js | 1 - src/navigation/botomTabNavigator.tsx | 1 - src/providers/coingecko/coingecko.ts | 2 +- src/providers/coingecko/converters.ts | 1 - src/providers/ecency/converters.ts | 32 +- src/providers/ecency/ePoint.ts | 2 +- src/providers/ecency/ecency.ts | 16 +- src/providers/hive-engine/converters.ts | 85 ++-- src/providers/hive-engine/hiveEngine.ts | 115 ++--- src/providers/hive-engine/hiveEngine.types.ts | 188 ++++--- src/providers/hive-trade/hiveTrade.ts | 18 +- src/providers/hive/dhive.js | 4 +- src/providers/hive/hive.types.ts | 10 +- src/providers/queries/editorQueries.ts | 8 +- src/providers/queries/index.ts | 32 +- .../queries/postQueries/postQueries.ts | 3 +- .../queries/postQueries/wavesQueries.ts | 198 ++++---- src/providers/queries/queryKeys.ts | 4 +- src/redux/actions/uiAction.ts | 4 +- src/redux/actions/walletActions.ts | 2 +- src/redux/reducers/uiReducer.ts | 9 +- .../assetDetails/children/activitiesList.tsx | 2 +- .../assetDetails/children/children.styles.ts | 14 +- .../assetDetails/children/coinBasics.tsx | 5 +- .../assetDetails/children/coinChart.tsx | 6 +- .../assetDetails/children/coinSummary.tsx | 2 +- .../children/delegationsModal.tsx | 6 +- .../assetDetails/children/rangeSelector.tsx | 39 +- .../styles/tokensSelectModa.styles.ts | 35 +- .../backupKeysScreen/backupKeysScreen.tsx | 2 +- .../importPrivateKeyModal.tsx | 4 +- src/screens/boost/screen/styles.ts | 2 +- .../drafts/container/draftsContainer.tsx | 2 +- src/screens/post/screen/postScreen.tsx | 18 +- .../settings/container/settingsContainer.tsx | 48 +- .../trade/children/swapTokenContent.tsx | 19 +- .../trade/children/useSwapCalculator.tsx | 48 +- .../trade/styles/assetChangeBtn.styles.ts | 45 +- .../trade/styles/errorSection.styles.ts | 68 +-- .../trade/styles/swapAmountInput.styles.ts | 95 ++-- .../trade/styles/swapFeeSection.styles.ts | 66 +-- .../trade/styles/tradeScreen.styles.ts | 16 +- src/screens/voters/screen/votersScreen.js | 6 +- src/screens/wallet/screen/walletScreen.tsx | 39 +- src/screens/wallet/styles/children.styles.ts | 12 +- .../wallet/styles/claimButton.styles.ts | 12 +- .../wallet/styles/manageAssets.styles.ts | 27 +- src/screens/waves/children/wavesHeader.tsx | 23 +- src/screens/waves/screen/wavesScreen.tsx | 307 ++++++----- src/screens/waves/styles/children.styles.ts | 22 +- .../waves/styles/wavesScreen.styles.ts | 6 +- src/utils/filterNsfwPost.js | 6 +- src/utils/hive-uri.ts | 11 +- src/utils/migrationHelpers.ts | 2 +- src/utils/number.ts | 6 +- src/utils/postParser.tsx | 57 +-- src/utils/time.js | 8 +- src/utils/vote.ts | 52 +- src/utils/wallet.ts | 475 +++++++++--------- 123 files changed, 2499 insertions(+), 2789 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 7a0f4f12e..61ffb6a3b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -12,5 +12,6 @@ }, "workbench.colorCustomizations": { "editorUnnecessaryCode.border": "#dd7aab" - } + }, + "java.compile.nullAnalysis.mode": "automatic" } \ No newline at end of file diff --git a/src/components/actionModal/view/actionModalStyles.ts b/src/components/actionModal/view/actionModalStyles.ts index 4b798b83b..03b899056 100644 --- a/src/components/actionModal/view/actionModalStyles.ts +++ b/src/components/actionModal/view/actionModalStyles.ts @@ -2,80 +2,77 @@ import { TextStyle, StyleSheet, ViewStyle, ImageStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ - modalStyle: { - backgroundColor: '$primaryBackgroundColor', - margin:0, - paddingTop:32, - paddingBottom:8, - }, + modalStyle: { + backgroundColor: '$primaryBackgroundColor', + margin: 0, + paddingTop: 32, + paddingBottom: 8, + }, - sheetContent: { - backgroundColor: '$primaryBackgroundColor', - position:'absolute', - bottom:0, - left:0, - right:0, - zIndex:999 - }, + sheetContent: { + backgroundColor: '$primaryBackgroundColor', + position: 'absolute', + bottom: 0, + left: 0, + right: 0, + zIndex: 999, + }, - container:{ - marginTop:16, - marginBottom:36, - paddingHorizontal:24, - alignItems:'center', - justifyContent:'space-between', - } as ViewStyle, + container: { + marginTop: 16, + marginBottom: 36, + paddingHorizontal: 24, + alignItems: 'center', + justifyContent: 'space-between', + } as ViewStyle, - imageStyle:{ - marginTop:8, - height:150, - width:'100%', - } as ImageStyle, + imageStyle: { + marginTop: 8, + height: 150, + width: '100%', + } as ImageStyle, - textContainer:{ - marginTop:32, - marginBottom:44, - } as ViewStyle, + textContainer: { + marginTop: 32, + marginBottom: 44, + } as ViewStyle, - title: { - color: '$primaryBlack', - alignSelf: 'center', - textAlign: 'center', - fontSize: 20, - fontWeight: '800', - } as TextStyle, + title: { + color: '$primaryBlack', + alignSelf: 'center', + textAlign: 'center', + fontSize: 20, + fontWeight: '800', + } as TextStyle, - bodyText: { - color: '$primaryBlack', - alignSelf: 'center', - textAlign: 'center', - fontSize: 16, - fontWeight: '600', - marginTop:4, - } as TextStyle, + bodyText: { + color: '$primaryBlack', + alignSelf: 'center', + textAlign: 'center', + fontSize: 16, + fontWeight: '600', + marginTop: 4, + } as TextStyle, - btnText:{ - color:'$pureWhite' - } as TextStyle, + btnText: { + color: '$pureWhite', + } as TextStyle, - button:{ + button: { + backgroundColor: '$primaryBlue', + minWidth: 150, + paddingVertical: 16, + marginVertical: 8, + borderRadius: 32, + justifyContent: 'center', + alignItems: 'center', + } as ViewStyle, - backgroundColor:'$primaryBlue', - minWidth:150, - paddingVertical:16, - marginVertical:8, - borderRadius:32, - justifyContent:'center', - alignItems:'center' - } as ViewStyle, - - - actionPanel:{ - width:'100%', - flexDirection:'row', - flexWrap:'wrap', - justifyContent:'space-around', - alignItems:'center', - } as ViewStyle, - -}) \ No newline at end of file + actionPanel: { + width: '100%', + flexDirection: 'row', + flexWrap: 'wrap', + justifyContent: 'space-around', + alignItems: 'center', + } as ViewStyle, +}); diff --git a/src/components/atoms/assetIcon/styles/assetIcon.styles.ts b/src/components/atoms/assetIcon/styles/assetIcon.styles.ts index da5fad288..b8df83c6e 100644 --- a/src/components/atoms/assetIcon/styles/assetIcon.styles.ts +++ b/src/components/atoms/assetIcon/styles/assetIcon.styles.ts @@ -1,22 +1,22 @@ -import { ViewStyle } from "react-native" -import EStyleSheet from "react-native-extended-stylesheet" -import { ImageStyle } from "react-native-fast-image" +import { ViewStyle } from 'react-native'; +import EStyleSheet from 'react-native-extended-stylesheet'; +import { ImageStyle } from 'react-native-fast-image'; export default EStyleSheet.create({ - hiveEngineWrapper: { - position: 'absolute', - top: -6, - right: 4, - borderRadius: 10, - padding: 1, - backgroundColor: '$pureWhite', - } as ViewStyle, - hiveEngineLogo: { - height: 14, - width: 14 - } as ImageStyle, - logo: { - height: 30, - width: 30, - } as ImageStyle, -}) \ No newline at end of file + hiveEngineWrapper: { + position: 'absolute', + top: -6, + right: 4, + borderRadius: 10, + padding: 1, + backgroundColor: '$pureWhite', + } as ViewStyle, + hiveEngineLogo: { + height: 14, + width: 14, + } as ImageStyle, + logo: { + height: 30, + width: 30, + } as ImageStyle, +}); diff --git a/src/components/atoms/writePostButton/container/writePostButton.tsx b/src/components/atoms/writePostButton/container/writePostButton.tsx index d7edfc85b..7bc020d6a 100644 --- a/src/components/atoms/writePostButton/container/writePostButton.tsx +++ b/src/components/atoms/writePostButton/container/writePostButton.tsx @@ -12,45 +12,45 @@ interface WritePostButtonProps { onPress: () => void; } -export const WritePostButton = forwardRef(({ placeholderId: placeholder, onPress }: WritePostButtonProps, ref) => { - const intl = useIntl(); +export const WritePostButton = forwardRef( + ({ placeholderId: placeholder, onPress }: WritePostButtonProps, ref) => { + const intl = useIntl(); - const animatedContainer = useRef(); + const animatedContainer = useRef(); - const isLoggedIn = useAppSelector((state) => state.application.isLoggedIn); - const currentAccount = useAppSelector((state) => state.account.currentAccount); + const isLoggedIn = useAppSelector((state) => state.application.isLoggedIn); + const currentAccount = useAppSelector((state) => state.account.currentAccount); - useImperativeHandle(ref, () => ({ - bounce: () => { - console.log('bouncing'); - if (animatedContainer.current) { - animatedContainer.current.swing(1000); + useImperativeHandle(ref, () => ({ + bounce: () => { + console.log('bouncing'); + if (animatedContainer.current) { + animatedContainer.current.swing(1000); + } + }, + })); + + const _onPress = () => { + if (!isLoggedIn) { + showLoginAlert({ intl }); + return; } - }, - })); + if (onPress) { + onPress(); + } + }; - const _onPress = () => { - if (!isLoggedIn) { - showLoginAlert({ intl }); - return; - } - if (onPress) { - onPress(); - } - }; - - return ( - - - - - - - {intl.formatMessage({ id: placeholder })} - + return ( + + + + + + {intl.formatMessage({ id: placeholder })} + - - - - ); -}); + + + ); + }, +); diff --git a/src/components/atoms/writePostButton/index.ts b/src/components/atoms/writePostButton/index.ts index c0314a461..f4df3d778 100644 --- a/src/components/atoms/writePostButton/index.ts +++ b/src/components/atoms/writePostButton/index.ts @@ -1 +1 @@ -export * from './container/writePostButton'; \ No newline at end of file +export * from './container/writePostButton'; diff --git a/src/components/basicHeader/view/basicHeaderView.tsx b/src/components/basicHeader/view/basicHeaderView.tsx index 83eefcabd..a73620f2a 100644 --- a/src/components/basicHeader/view/basicHeaderView.tsx +++ b/src/components/basicHeader/view/basicHeaderView.tsx @@ -196,8 +196,8 @@ const BasicHeaderView = ({ size={28} onPress={() => handleBrowserIconPress()} iconStyle={styles.rightIcon} - name={'open-in-browser'} - iconType={'MaterialIcons'} + name="open-in-browser" + iconType="MaterialIcons" /> )} diff --git a/src/components/basicUIElements/view/placeHolder/boostPlaceHolderView.js b/src/components/basicUIElements/view/placeHolder/boostPlaceHolderView.js index b5f4f7e3b..d25579261 100644 --- a/src/components/basicUIElements/view/placeHolder/boostPlaceHolderView.js +++ b/src/components/basicUIElements/view/placeHolder/boostPlaceHolderView.js @@ -16,28 +16,22 @@ const BoostPlaceHolder = () => { const isDarkTheme = useSelector((state) => state.application.isDarkTeme); const color = isDarkTheme ? '#2e3d51' : '#f5f5f5'; times(parseInt(ratio), (i) => { - listElements.push( - - - + listElements.push( + + + + + + - - - - + , ); }); diff --git a/src/components/basicUIElements/view/placeHolder/commentPlaceHolderView.js b/src/components/basicUIElements/view/placeHolder/commentPlaceHolderView.js index 1b7a25223..5fe4607a1 100644 --- a/src/components/basicUIElements/view/placeHolder/commentPlaceHolderView.js +++ b/src/components/basicUIElements/view/placeHolder/commentPlaceHolderView.js @@ -11,7 +11,6 @@ const CommentPlaceHolderView = () => { height: 72, }; - const isDarkTheme = useSelector((state) => state.application.isDarkTheme); const color = isDarkTheme ? '#2e3d51' : '#f5f5f5'; @@ -33,9 +32,6 @@ const CommentPlaceHolderView = () => { /> ); - - - }; export default CommentPlaceHolderView; diff --git a/src/components/basicUIElements/view/placeHolder/communitiesPlaceHolder.js b/src/components/basicUIElements/view/placeHolder/communitiesPlaceHolder.js index 1d571a913..7a71a9584 100644 --- a/src/components/basicUIElements/view/placeHolder/communitiesPlaceHolder.js +++ b/src/components/basicUIElements/view/placeHolder/communitiesPlaceHolder.js @@ -7,7 +7,7 @@ import { useSelector } from 'react-redux'; import styles from './postCardPlaceHolderStyles'; // TODO: make container for place holder wrapper after alpha const PostCardPlaceHolder = () => { - const isDarkTheme = useSelector((state) => state.application.isDarkTheme) + const isDarkTheme = useSelector((state) => state.application.isDarkTheme); const color = isDarkTheme ? '#2e3d51' : '#f5f5f5'; return ( @@ -25,6 +25,5 @@ const PostCardPlaceHolder = () => { ); - }; export default PostCardPlaceHolder; diff --git a/src/components/basicUIElements/view/placeHolder/listItemPlaceHolderView.js b/src/components/basicUIElements/view/placeHolder/listItemPlaceHolderView.js index fed16866a..821f58894 100644 --- a/src/components/basicUIElements/view/placeHolder/listItemPlaceHolderView.js +++ b/src/components/basicUIElements/view/placeHolder/listItemPlaceHolderView.js @@ -7,7 +7,6 @@ import { useSelector } from 'react-redux'; import styles from './listItemPlaceHolderStyles'; const ListItemPlaceHolderView = () => { - const isDarkTheme = useSelector((state) => state.application.isDarkTheme); const color = isDarkTheme ? '#2e3d51' : '#f5f5f5'; return ( @@ -27,7 +26,6 @@ const ListItemPlaceHolderView = () => { ); - }; export default ListItemPlaceHolderView; diff --git a/src/components/basicUIElements/view/placeHolder/postCardPlaceHolderView.js b/src/components/basicUIElements/view/placeHolder/postCardPlaceHolderView.js index 77957ed17..2a2ca1ccd 100644 --- a/src/components/basicUIElements/view/placeHolder/postCardPlaceHolderView.js +++ b/src/components/basicUIElements/view/placeHolder/postCardPlaceHolderView.js @@ -4,6 +4,7 @@ import LottieView from 'lottie-react-native'; import { useSelector } from 'react-redux'; import styles from './postCardPlaceHolderStyles'; import getWindowDimensions from '../../../../utils/getWindowDimensions'; + const PostCardPlaceHolder = () => { const animationStyle = { width: getWindowDimensions().nativeWidth - 32, @@ -29,6 +30,5 @@ const PostCardPlaceHolder = () => { /> ); - }; export default PostCardPlaceHolder; diff --git a/src/components/basicUIElements/view/placeHolder/postPlaceHolderView.js b/src/components/basicUIElements/view/placeHolder/postPlaceHolderView.js index 29ced2278..747148008 100644 --- a/src/components/basicUIElements/view/placeHolder/postPlaceHolderView.js +++ b/src/components/basicUIElements/view/placeHolder/postPlaceHolderView.js @@ -4,8 +4,8 @@ import LottieView from 'lottie-react-native'; import { useSelector } from 'react-redux'; import getWindowDimensions from '../../../../utils/getWindowDimensions'; -const PostPlaceHolder = () => { +const PostPlaceHolder = () => { const isDarkTheme = useSelector((state) => state.application.isDarkTheme); const color = isDarkTheme ? '#2e3d51' : '#f5f5f5'; @@ -27,7 +27,6 @@ const PostPlaceHolder = () => { /> ); - }; export default PostPlaceHolder; diff --git a/src/components/basicUIElements/view/placeHolder/profileSummaryPlaceHolder.js b/src/components/basicUIElements/view/placeHolder/profileSummaryPlaceHolder.js index 303411ba8..7061ce565 100644 --- a/src/components/basicUIElements/view/placeHolder/profileSummaryPlaceHolder.js +++ b/src/components/basicUIElements/view/placeHolder/profileSummaryPlaceHolder.js @@ -29,7 +29,6 @@ const ProfileSummaryPlaceHolder = () => { ); - }; export default ProfileSummaryPlaceHolder; diff --git a/src/components/basicUIElements/view/placeHolder/walletDetailsPlaceHolder.js b/src/components/basicUIElements/view/placeHolder/walletDetailsPlaceHolder.js index 535a1edf6..873973d20 100644 --- a/src/components/basicUIElements/view/placeHolder/walletDetailsPlaceHolder.js +++ b/src/components/basicUIElements/view/placeHolder/walletDetailsPlaceHolder.js @@ -29,7 +29,6 @@ const WalletDetailsPlaceHolder = () => { const isDarkTheme = useSelector((state) => state.application.isDarkTheme); const color = isDarkTheme ? '#2e3d51' : '#f5f5f5'; - return ( @@ -37,12 +36,8 @@ const WalletDetailsPlaceHolder = () => { {listPlaceHolderView(color)} - ) - -} - - - + ); +}; export default WalletDetailsPlaceHolder; /* eslint-enable */ diff --git a/src/components/basicUIElements/view/userListItem/userListItemStyles.js b/src/components/basicUIElements/view/userListItem/userListItemStyles.js index facad4449..7ca98d2ef 100644 --- a/src/components/basicUIElements/view/userListItem/userListItemStyles.js +++ b/src/components/basicUIElements/view/userListItem/userListItemStyles.js @@ -101,6 +101,4 @@ export default EStyleSheet.create({ tooltipText: { color: '$primaryDarkText', }, - - }); diff --git a/src/components/basicUIElements/view/walletLineItem/walletLineItemStyles.js b/src/components/basicUIElements/view/walletLineItem/walletLineItemStyles.js index ca6901fd9..f0a0f188e 100644 --- a/src/components/basicUIElements/view/walletLineItem/walletLineItemStyles.js +++ b/src/components/basicUIElements/view/walletLineItem/walletLineItemStyles.js @@ -80,8 +80,8 @@ export default EStyleSheet.create({ justifyContent: 'center', alignSelf: 'center', }, - cancelIcon:{ - marginLeft:8, + cancelIcon: { + marginLeft: 8, }, dropdownWrapper: { flex: 1, diff --git a/src/components/beneficiaryModal/beneficiaryModal.tsx b/src/components/beneficiaryModal/beneficiaryModal.tsx index ff83cc9e8..0efe6945d 100644 --- a/src/components/beneficiaryModal/beneficiaryModal.tsx +++ b/src/components/beneficiaryModal/beneficiaryModal.tsx @@ -3,31 +3,31 @@ import { View, FlatList, Text } from 'react-native'; import { useIntl } from 'react-intl'; import { isArray, debounce } from 'lodash'; +import EStyleSheet from 'react-native-extended-stylesheet'; +import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import { lookupAccounts } from '../../providers/hive/dhive'; import { FormInput, MainButton, TextButton } from '..'; import styles from './beneficiaryModalStyles'; -import EStyleSheet from 'react-native-extended-stylesheet'; import IconButton from '../iconButton'; -import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import { useAppSelector } from '../../hooks'; import { Beneficiary } from '../../redux/reducers/editorReducer'; import { TEMP_BENEFICIARIES_ID } from '../../redux/constants/constants'; interface BeneficiaryModal { - username:string, - draftId:string, - handleOnSaveBeneficiaries:()=>void + username: string; + draftId: string; + handleOnSaveBeneficiaries: () => void; } const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { const intl = useIntl(); - const beneficiariesMap = useAppSelector(state => state.editor.beneficiariesMap) + const beneficiariesMap = useAppSelector((state) => state.editor.beneficiariesMap); const [beneficiaries, setBeneficiaries] = useState([ - { account: username, weight: 10000, isValid: true}, + { account: username, weight: 10000, isValid: true }, ]); const [newUsername, setNewUsername] = useState(''); @@ -37,14 +37,13 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { const [newEditable, setNewEditable] = useState(false); useEffect(() => { - readTempBeneficiaries(); + readTempBeneficiaries(); }, [draftId]); - const readTempBeneficiaries = async () => { - if(beneficiariesMap){ + if (beneficiariesMap) { const tempBeneficiaries = beneficiariesMap[draftId || TEMP_BENEFICIARIES_ID]; - + if (isArray(tempBeneficiaries)) { tempBeneficiaries.forEach((item) => { item.isValid = true; @@ -52,28 +51,24 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { setBeneficiaries(tempBeneficiaries); } } - }; - const _onSavePress = () => { - if(newEditable){ + if (newEditable) { beneficiaries.push({ - account:newUsername, - weight:newWeight - }) + account: newUsername, + weight: newWeight, + }); } handleOnSaveBeneficiaries(beneficiaries); - } - + }; const _addAccount = () => { - - if(isUsernameValid && isWeightValid){ + if (isUsernameValid && isWeightValid) { beneficiaries.push({ - account:newUsername, - weight:newWeight, - }) + account: newUsername, + weight: newWeight, + }); setBeneficiaries([...beneficiaries]); } @@ -84,43 +79,33 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { setNewEditable(true); }; - - const _onWeightInputChange = (value) => { - let _value = (parseInt(value, 10) || 0) * 100; + const _value = (parseInt(value, 10) || 0) * 100; const _diff = _value - newWeight; beneficiaries[0].weight = beneficiaries[0].weight - _diff; - setNewWeight(_value) - setIsWeightValid(_value > 0 && _value <= 10000) + setNewWeight(_value); + setIsWeightValid(_value > 0 && _value <= 10000); setBeneficiaries([...beneficiaries]); }; - const _lookupAccounts = debounce((username) => { - lookupAccounts(username).then((res) => { - const isValid = res.includes(username) - //check if username duplicates else lookup contacts, done here to avoid debounce and post call mismatch - const notExistAlready = !beneficiaries.find((item)=>item.account === username); - setIsUsernameValid(isValid && notExistAlready) + const isValid = res.includes(username); + // check if username duplicates else lookup contacts, done here to avoid debounce and post call mismatch + const notExistAlready = !beneficiaries.find((item) => item.account === username); + setIsUsernameValid(isValid && notExistAlready); }); - }, 1000) - - + }, 1000); const _onUsernameInputChange = (value) => { setNewUsername(value); _lookupAccounts(value); }; - - const _isValid = () => { return !newEditable || (isUsernameValid && isWeightValid); }; - - const _renderHeader = () => ( @@ -138,23 +123,20 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { - ) - + ); const _renderInput = () => { - const _onCancelPress = () => { - if(newWeight){ + if (newWeight) { beneficiaries[0].weight = beneficiaries[0].weight + newWeight; - setBeneficiaries([...beneficiaries]) + setBeneficiaries([...beneficiaries]); setNewWeight(0); } setNewEditable(false); setIsWeightValid(false); setIsUsernameValid(false); setNewUsername(''); - - } + }; return ( @@ -165,8 +147,8 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { inputStyle={styles.weightFormInput} wrapperStyle={styles.weightFormInputWrapper} onChange={(value) => _onWeightInputChange(value)} - onBlur={() => {}}//_onBlur(item)} - keyboardType='numeric' + onBlur={() => {}} // _onBlur(item)} + keyboardType="numeric" /> @@ -187,40 +169,36 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { /> - - + ); }; - const _renderFooter = () => ( <> {newEditable && _renderInput()} - - + - - ) - + ); const _renderItem = ({ item, index }) => { const _isCurrentUser = item.account === username; @@ -229,8 +207,7 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { beneficiaries[0].weight = beneficiaries[0].weight + item.weight; beneficiaries.splice(index, 1); setBeneficiaries([...beneficiaries]); - } - + }; return ( @@ -241,7 +218,7 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { value={`${item.weight / 100}`} inputStyle={styles.weightFormInput} wrapperStyle={styles.weightFormInputWrapper} - /> + /> @@ -256,28 +233,25 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { /> {!_isCurrentUser ? ( - - ):( - + ) : ( + )} - ); }; - const isAllValid = _isValid(); return ( - 0) { - //weight correction algorithm. + // weight correction algorithm. let othersWeight = 0; tempBeneficiaries.forEach((item, index) => { if (index > 0) { @@ -100,7 +100,7 @@ const BeneficiarySelectionContent = ({ : [DEFAULT_BENEFICIARY]; if (isArray(tempBeneficiaries) && tempBeneficiaries.length > 0) { - //weight correction algorithm. + // weight correction algorithm. let othersWeight = 0; tempBeneficiaries.forEach((item, index) => { if (index > 0) { @@ -114,7 +114,7 @@ const BeneficiarySelectionContent = ({ }; const _saveBeneficiaries = (value: Beneficiary[]) => { - const filteredBeneficiaries = value.filter((item) => item.account !== username); //remove default beneficiary from array while saving + const filteredBeneficiaries = value.filter((item) => item.account !== username); // remove default beneficiary from array while saving if (handleSaveBeneficiary) { handleSaveBeneficiary(filteredBeneficiaries); } else { @@ -151,7 +151,7 @@ const BeneficiarySelectionContent = ({ }; const _onWeightInputChange = (value: string) => { - let _value = (parseInt(value, 10) || 0) * 100; + const _value = (parseInt(value, 10) || 0) * 100; const _diff = _value - newWeight; const newAuthorWeight = beneficiaries[0].weight - _diff; @@ -165,7 +165,7 @@ const BeneficiarySelectionContent = ({ const _lookupAccounts = debounce((username) => { lookupAccounts(username).then((res) => { const isValid = res.includes(username); - //check if username duplicates else lookup contacts, done here to avoid debounce and post call mismatch + // check if username duplicates else lookup contacts, done here to avoid debounce and post call mismatch const notExistAlready = !beneficiaries.find((item) => item.account === username); setIsUsernameValid(isValid && notExistAlready); }); diff --git a/src/components/bottomTabBar/view/bottomTabBarView.tsx b/src/components/bottomTabBar/view/bottomTabBarView.tsx index 7fcafbf9e..b470aa61d 100644 --- a/src/components/bottomTabBar/view/bottomTabBarView.tsx +++ b/src/components/bottomTabBar/view/bottomTabBarView.tsx @@ -7,6 +7,7 @@ import { SafeAreaView, View, TouchableOpacity, Alert } from 'react-native'; // Constants import { useDispatch } from 'react-redux'; import { BottomTabBarProps } from '@react-navigation/bottom-tabs'; +import { useIntl } from 'react-intl'; import ROUTES from '../../../constants/routeNames'; // Styles @@ -16,7 +17,6 @@ import scalePx from '../../../utils/scalePx'; import { showReplyModal, updateActiveBottomTab } from '../../../redux/actions/uiAction'; import { useAppSelector } from '../../../hooks'; import showLoginAlert from '../../../utils/showLoginAlert'; -import { useIntl } from 'react-intl'; const BottomTabBarView = ({ state: { routes, index }, @@ -31,19 +31,15 @@ const BottomTabBarView = ({ dispatch(updateActiveBottomTab(routes[index].name)); }, [index]); - - const _jumpTo = (route, isFocused) => { - if (route.name === ROUTES.TABBAR.POST_BUTTON) { - - if(!isLoggedIn){ - showLoginAlert({intl}) + if (!isLoggedIn) { + showLoginAlert({ intl }); return; } - + if (routes[index].name === ROUTES.TABBAR.WAVES) { - dispatch(showReplyModal({mode:'wave'})); + dispatch(showReplyModal({ mode: 'wave' })); } else { navigation.navigate(ROUTES.SCREENS.EDITOR, { key: 'editor_post' }); } @@ -63,8 +59,6 @@ const BottomTabBarView = ({ } }; - - const _tabButtons = routes.map((route, idx) => { const { tabBarActiveTintColor, tabBarInactiveTintColor } = descriptors[route.key].options; const isFocused = index == idx; @@ -88,7 +82,6 @@ const BottomTabBarView = ({ _iconProps.iconType = 'MaterialCommunityIcons'; _tabBarIcon = ; break; - } return ( @@ -98,8 +91,6 @@ const BottomTabBarView = ({ ); }); - - return {_tabButtons}; }; diff --git a/src/components/comment/view/commentView.tsx b/src/components/comment/view/commentView.tsx index 1482a0aff..68cb3678a 100644 --- a/src/components/comment/view/commentView.tsx +++ b/src/components/comment/view/commentView.tsx @@ -73,7 +73,7 @@ const CommentView = ({ const _handleOnContentPress = () => { openReplyThread(comment); - } + }; const _handleOnReplyPress = () => { if (isLoggedIn) { @@ -97,7 +97,6 @@ const CommentView = ({ ); const _renderComment = () => { - const _hideContent = isMuted || comment.author_reputation < 25 || comment.net_rshares < 0; return ( @@ -219,9 +218,9 @@ const CommentView = ({ const customContainerStyle = _depth > 1 ? { - paddingLeft: (_depth - 2) * 44, - backgroundColor: EStyleSheet.value('$primaryLightBackground'), - } + paddingLeft: (_depth - 2) * 44, + backgroundColor: EStyleSheet.value('$primaryLightBackground'), + } : null; return ( diff --git a/src/components/comments/container/commentsContainer.tsx b/src/components/comments/container/commentsContainer.tsx index 7e10ac8e5..1471eb9b2 100644 --- a/src/components/comments/container/commentsContainer.tsx +++ b/src/components/comments/container/commentsContainer.tsx @@ -52,7 +52,7 @@ const CommentsContainer = ({ incrementRepliesCount, handleOnReplyPress, handleOnCommentsLoaded, - postType + postType, }) => { const navigation = useNavigation(); const postsCachePrimer = postQueries.usePostsCachePrimer(); @@ -172,7 +172,7 @@ const CommentsContainer = ({ handleOnCommentsLoaded(); } }) - .catch(() => { }); + .catch(() => {}); } }; @@ -244,13 +244,11 @@ const CommentsContainer = ({ }); }; - const _handleOnUserPress = (username) => { if (username) { - dispatch(showProfileModal(username)) + dispatch(showProfileModal(username)); } - - } + }; const _openReplyThread = (comment) => { postsCachePrimer.cachePost(comment); diff --git a/src/components/comments/view/commentsView.tsx b/src/components/comments/view/commentsView.tsx index 11e84457a..aeb91d9d6 100644 --- a/src/components/comments/view/commentsView.tsx +++ b/src/components/comments/view/commentsView.tsx @@ -42,7 +42,7 @@ const CommentsView = ({ incrementRepliesCount, postContentView, isLoading, - postType + postType, }) => { const [selectedComment, setSelectedComment] = useState(null); const intl = useIntl(); @@ -51,7 +51,6 @@ const CommentsView = ({ const postInteractionRef = useRef(null); const _openCommentMenu = (item) => { - if (handleOnOptionsPress) { handleOnOptionsPress(item); } else if (commentMenu.current) { @@ -79,8 +78,8 @@ const CommentsView = ({ const _onUpvotePress = ({ content, anchorRect, showPayoutDetails, onVotingStart }) => { if (upvotePopoverRef.current) { - - const postType = content.parent_author === 'ecency.waves' ? PostTypes.WAVE : PostTypes.COMMENT; + const postType = + content.parent_author === 'ecency.waves' ? PostTypes.WAVE : PostTypes.COMMENT; upvotePopoverRef.current.showPopover({ anchorRect, @@ -147,9 +146,9 @@ const CommentsView = ({ const styleOerride = commentNumber > 1 ? { - backgroundColor: EStyleSheet.value('$primaryLightBackground'), - marginTop: 8, - } + backgroundColor: EStyleSheet.value('$primaryLightBackground'), + marginTop: 8, + } : null; const _renderEmptyContent = () => { @@ -169,7 +168,7 @@ const CommentsView = ({ return ( item.author + item.permlink} renderItem={_renderItem} diff --git a/src/components/draftListItem/view/draftListItemView.tsx b/src/components/draftListItem/view/draftListItemView.tsx index 18a757eaa..1200b8406 100644 --- a/src/components/draftListItem/view/draftListItemView.tsx +++ b/src/components/draftListItem/view/draftListItemView.tsx @@ -5,6 +5,7 @@ import { injectIntl } from 'react-intl'; // Utils import FastImage from 'react-native-fast-image'; import EStyleSheet from 'react-native-extended-stylesheet'; +import ESStyleSheet from 'react-native-extended-stylesheet'; import { getTimeFromNow } from '../../../utils/time'; // Components @@ -16,7 +17,6 @@ import { OptionsModal } from '../../atoms'; import styles from './draftListItemStyles'; import { ScheduledPostStatus } from '../../../providers/ecency/ecency.types'; import { PopoverWrapper } from '../../popoverWrapper/popoverWrapperView'; -import ESStyleSheet from 'react-native-extended-stylesheet'; const DraftListItemView = ({ title, diff --git a/src/components/editorElements/titleArea/view/titleAreaView.js b/src/components/editorElements/titleArea/view/titleAreaView.js index 97e8cb277..2a065d3a8 100644 --- a/src/components/editorElements/titleArea/view/titleAreaView.js +++ b/src/components/editorElements/titleArea/view/titleAreaView.js @@ -1,7 +1,6 @@ import React, { Component } from 'react'; import { View } from 'react-native'; -import { useSelector } from 'react-redux'; -import { connect } from 'react-redux'; +import { useSelector, connect } from 'react-redux'; // Constants // Components @@ -53,7 +52,6 @@ class TitleAreaView extends Component { const { isDarkTheme } = this.props; return ( - this._handleOnChange(textT)} value={text} /> - ); } } - - const mapStateToProps = (state) => ({ isDarkTheme: state.application.isDarkTheme, }); export default connect(mapStateToProps)(TitleAreaView); - - - diff --git a/src/components/formInput/view/formInputView.tsx b/src/components/formInput/view/formInputView.tsx index 5cc7c5b69..0e40399bf 100644 --- a/src/components/formInput/view/formInputView.tsx +++ b/src/components/formInput/view/formInputView.tsx @@ -13,6 +13,7 @@ import FastImage from 'react-native-fast-image'; import Popover, { usePopover } from 'react-native-modal-popover'; // Components +import { useSelector } from 'react-redux'; import { TextInput } from '../../textInput'; import { Icon } from '../../icon'; // Utils @@ -20,7 +21,6 @@ import { getResizedAvatar } from '../../../utils/image'; // Styles import styles from './formInputStyles'; -import { useSelector } from 'react-redux'; interface Props extends TextInputProps { type: string; @@ -133,7 +133,7 @@ const FormInputView = ({ const _renderInfoIconWithPopover = () => ( - + {({ currentAccount, isLoggedIn, isLoginDone }) => { const _user = isReverse && selectedUser ? selectedUser : currentAccount; @@ -58,7 +57,6 @@ const HeaderContainer = ({ selectedUser, isReverse, handleOnBackPress, hideUser, ); }} - ); }; diff --git a/src/components/insertLinkModal/insertLinkModal.tsx b/src/components/insertLinkModal/insertLinkModal.tsx index 12223206f..8cacb91fc 100644 --- a/src/components/insertLinkModal/insertLinkModal.tsx +++ b/src/components/insertLinkModal/insertLinkModal.tsx @@ -4,6 +4,7 @@ import { Platform, Text, TouchableOpacity, View, ActivityIndicator } from 'react import { renderPostBody } from '@ecency/render-helper'; import { ScrollView } from 'react-native-gesture-handler'; import Clipboard from '@react-native-clipboard/clipboard'; +import EStyleSheet from 'react-native-extended-stylesheet'; import { MainButton, PostBody, TextButton } from '..'; import styles from './insertLinkModalStyles'; import TextInput from '../textInput'; @@ -12,7 +13,6 @@ import { isStringWebLink } from '../markdownEditor/children/formats/utils'; import applyWebLinkFormat from '../markdownEditor/children/formats/applyWebLinkFormat'; import getWindowDimensions from '../../utils/getWindowDimensions'; import Modal from '../modal'; -import EStyleSheet from 'react-native-extended-stylesheet'; interface InsertLinkModalProps { handleOnInsertLink: ({ @@ -78,7 +78,7 @@ export const InsertLinkModal = forwardRef( const labelText = selectedUrlType === 2 ? url.split('/').pop() : selectedUrlType === 1 ? '' : label; applyWebLinkFormat({ - item: { text: labelText, url: url }, + item: { text: labelText, url }, text: '', selection: { start: 0, end: 0 }, setTextAndSelection: _setFormattedTextAndSelection, @@ -98,7 +98,7 @@ export const InsertLinkModal = forwardRef( }; const _setFormattedTextAndSelection = ({ selection, text }) => { - setPreviewBody(renderPostBody(text, true, Platform.OS === 'ios' ? false : true)); + setPreviewBody(renderPostBody(text, true, Platform.OS !== 'ios')); setFormattedText(text); }; @@ -127,7 +127,7 @@ export const InsertLinkModal = forwardRef( setIsUrlValid(false); return; } - handleOnInsertLink({ snippetText: formattedText, selection: selection }); + handleOnInsertLink({ snippetText: formattedText, selection }); setIsUrlValid(true); }; const _renderFloatingPanel = () => { diff --git a/src/components/organisms/quickProfileModal/children/quickProfileContent.tsx b/src/components/organisms/quickProfileModal/children/quickProfileContent.tsx index e6ec0b5e6..0722d22b5 100644 --- a/src/components/organisms/quickProfileModal/children/quickProfileContent.tsx +++ b/src/components/organisms/quickProfileModal/children/quickProfileContent.tsx @@ -1,272 +1,252 @@ -import React, { useEffect, useState, useMemo } from 'react' -import { useIntl } from 'react-intl' -import { View, Alert } from 'react-native' -import { ProfileStats, StatsData } from './profileStats' -import { MainButton } from '../../..' -import { addFavorite, checkFavorite, deleteFavorite } from '../../../../providers/ecency/ecency' -import { followUser, getFollows, getRelationship, getUser } from '../../../../providers/hive/dhive' -import { getRcPower, getVotingPower } from '../../../../utils/manaBar' -import styles from './quickProfileStyles' -import { ProfileBasic } from './profileBasic' -import { parseReputation } from '../../../../utils/user' +import React, { useEffect, useState, useMemo } from 'react'; +import { useIntl } from 'react-intl'; +import { View, Alert } from 'react-native'; +import { ProfileStats, StatsData } from './profileStats'; +import { MainButton } from '../../..'; +import { addFavorite, checkFavorite, deleteFavorite } from '../../../../providers/ecency/ecency'; +import { followUser, getFollows, getRelationship, getUser } from '../../../../providers/hive/dhive'; +import { getRcPower, getVotingPower } from '../../../../utils/manaBar'; +import styles from './quickProfileStyles'; +import { ProfileBasic } from './profileBasic'; +import { parseReputation } from '../../../../utils/user'; import { default as ROUTES } from '../../../../constants/routeNames'; -import { ActionPanel } from './actionPanel' -import { getTimeFromNowNative } from '../../../../utils/time' -import { useAppDispatch, useAppSelector } from '../../../../hooks' -import { toastNotification } from '../../../../redux/actions/uiAction' -import bugsnapInstance from '../../../../config/bugsnag' -import RootNavigation from '../../../../navigation/rootNavigation' +import { ActionPanel } from './actionPanel'; +import { getTimeFromNowNative } from '../../../../utils/time'; +import { useAppDispatch, useAppSelector } from '../../../../hooks'; +import { toastNotification } from '../../../../redux/actions/uiAction'; +import bugsnapInstance from '../../../../config/bugsnag'; +import RootNavigation from '../../../../navigation/rootNavigation'; interface QuickProfileContentProps { - username: string, - onClose: () => void; + username: string; + onClose: () => void; } -export const QuickProfileContent = ({ - username, - onClose -}: QuickProfileContentProps) => { - const intl = useIntl(); - const dispatch = useAppDispatch(); +export const QuickProfileContent = ({ username, onClose }: QuickProfileContentProps) => { + const intl = useIntl(); + const dispatch = useAppDispatch(); - const currentAccount = useAppSelector((state) => state.account.currentAccount); - const pinCode = useAppSelector((state) => state.application.pin); - const isLoggedIn = useAppSelector((state) => state.application.isLoggedIn); + const currentAccount = useAppSelector((state) => state.account.currentAccount); + const pinCode = useAppSelector((state) => state.application.pin); + const isLoggedIn = useAppSelector((state) => state.application.isLoggedIn); - const [isLoading, setIsLoading] = useState(false); - const [user, setUser] = useState(null); - const [follows, setFollows] = useState(null); - const [isFollowing, setIsFollowing] = useState(false); - const [isMuted, setIsMuted] = useState(false); - const [isFavourite, setIsFavourite] = useState(false); + const [isLoading, setIsLoading] = useState(false); + const [user, setUser] = useState(null); + const [follows, setFollows] = useState(null); + const [isFollowing, setIsFollowing] = useState(false); + const [isMuted, setIsMuted] = useState(false); + const [isFavourite, setIsFavourite] = useState(false); - const isOwnProfile = currentAccount && currentAccount.name === username; - const currentAccountName = currentAccount ? currentAccount.name : null; - const isProfileLoaded = (user && follows) ? true : false; + const isOwnProfile = currentAccount && currentAccount.name === username; + const currentAccountName = currentAccount ? currentAccount.name : null; + const isProfileLoaded = !!(user && follows); - useEffect(() => { - if (username) { - _fetchUser(); - _fetchExtraUserData(); - } else { - setUser(null); + useEffect(() => { + if (username) { + _fetchUser(); + _fetchExtraUserData(); + } else { + setUser(null); + } + }, [username]); + + // NETWORK CALLS + const _fetchUser = async () => { + setIsLoading(true); + try { + const _user = await getUser(username, isOwnProfile); + setUser(_user); + } catch (error) { + setIsLoading(false); + } + }; + + const _fetchExtraUserData = async () => { + try { + if (username) { + let _isFollowing; + let _isMuted; + let _isFavourite; + let follows; + + if (!isOwnProfile) { + const res = await getRelationship(currentAccountName, username); + _isFollowing = res && res.follows; + _isMuted = res && res.ignores; + _isFavourite = await checkFavorite(username); } - }, [username]) - - //NETWORK CALLS - const _fetchUser = async () => { - setIsLoading(true); try { - const _user = await getUser(username, isOwnProfile); - setUser(_user) - } catch (error) { - setIsLoading(false); + follows = await getFollows(username); + } catch (err) { + follows = null; } + + setFollows(follows); + setIsFollowing(_isFollowing); + setIsMuted(_isMuted); + setIsFavourite(_isFavourite); + setIsLoading(false); + } + } catch (error) { + console.warn('Failed to fetch complete profile data', error); + Alert.alert( + intl.formatMessage({ + id: 'alert.fail', + }), + error.message || error.toString(), + ); + setIsLoading(false); + } + }; + + const _onFollowPress = async () => { + try { + const follower = currentAccountName; + const following = username; + + setIsLoading(true); + await followUser(currentAccount, pinCode, { + follower, + following, + }); + + setIsLoading(false); + setIsFollowing(true); + dispatch( + toastNotification( + intl.formatMessage({ + id: isFollowing ? 'alert.success_unfollow' : 'alert.success_follow', + }), + ), + ); + } catch (err) { + setIsLoading(false); + console.warn('Failed to follow user', err); + bugsnapInstance.notify(err); + Alert.alert(intl.formatMessage({ id: 'alert.fail' }), err.message); + } + }; + + const _onFavouritePress = async () => { + try { + setIsLoading(true); + let favoriteAction; + + if (isFavourite) { + favoriteAction = deleteFavorite; + } else { + favoriteAction = addFavorite; + } + + await favoriteAction(username); + + dispatch( + toastNotification( + intl.formatMessage({ + id: isFavourite ? 'alert.success_unfavorite' : 'alert.success_favorite', + }), + ), + ); + setIsFavourite(!isFavourite); + setIsLoading(false); + } catch (error) { + console.warn('Failed to perform favorite action'); + setIsLoading(false); + Alert.alert( + intl.formatMessage({ + id: 'alert.fail', + }), + error.message || error.toString(), + ); + } + }; + + // UI CALLBACKS + + const _openFullProfile = () => { + const params = { + username, + reputation: user ? user.reputation : null, }; + RootNavigation.navigate({ + name: ROUTES.SCREENS.PROFILE, + params, + key: username, + }); - const _fetchExtraUserData = async () => { - try { - if (username) { - let _isFollowing; - let _isMuted; - let _isFavourite; - let follows; - - if (!isOwnProfile) { - const res = await getRelationship(currentAccountName, username); - _isFollowing = res && res.follows; - _isMuted = res && res.ignores; - _isFavourite = await checkFavorite(username); - } - - try { - follows = await getFollows(username); - } catch (err) { - follows = null; - } - - - setFollows(follows); - setIsFollowing(_isFollowing); - setIsMuted(_isMuted) - setIsFavourite(_isFavourite) - setIsLoading(false); - - } - } catch (error) { - console.warn('Failed to fetch complete profile data', error); - Alert.alert( - intl.formatMessage({ - id: 'alert.fail', - }), - error.message || error.toString(), - ); - setIsLoading(false); - } - }; - - - const _onFollowPress = async () => { - try { - const follower = currentAccountName - const following = username; - - setIsLoading(true); - await followUser(currentAccount, pinCode, { - follower, - following, - }) - - setIsLoading(false); - setIsFollowing(true) - dispatch( - toastNotification( - intl.formatMessage({ - id: isFollowing ? 'alert.success_unfollow' : 'alert.success_follow', - }), - ), - ); - } - catch (err) { - setIsLoading(false); - console.warn("Failed to follow user", err) - bugsnapInstance.notify(err); - Alert.alert(intl.formatMessage({ id: 'alert.fail' }), err.message) - } + if (onClose) { + onClose(); } + }; - const _onFavouritePress = async () => { - try { - setIsLoading(true); - let favoriteAction; + // extract prop values + let _votingPower = ''; + let _resourceCredits = ''; + let _followerCount = 0; + let _followingCount = 0; + let _postCount = 0; + let _about = ''; + let _reputation = 0; + let _createdData = null; - if (isFavourite) { - favoriteAction = deleteFavorite; - } else { - favoriteAction = addFavorite; - } + if (isProfileLoaded) { + _votingPower = getVotingPower(user).toFixed(1); + _resourceCredits = getRcPower(user).toFixed(0); + _postCount = user.post_count || 0; + _about = user.about?.profile?.about || ''; + _reputation = parseReputation(user.reputation); + _createdData = getTimeFromNowNative(user.created); - await favoriteAction(username) - - dispatch( - toastNotification( - intl.formatMessage({ - id: isFavourite ? 'alert.success_unfavorite' : 'alert.success_favorite', - }), - ), - ); - setIsFavourite(!isFavourite); - setIsLoading(false); - } - - catch (error) { - console.warn('Failed to perform favorite action'); - setIsLoading(false); - Alert.alert( - intl.formatMessage({ - id: 'alert.fail', - }), - error.message || error.toString(), - ); - } + if (follows) { + _followerCount = follows.follower_count || 0; + _followingCount = follows.following_count || 0; } + } + const statsData1 = [ + { label: intl.formatMessage({ id: 'profile.follower' }), value: _followerCount }, + { label: intl.formatMessage({ id: 'profile.following' }), value: _followingCount }, + { label: intl.formatMessage({ id: 'profile.post' }), value: _postCount }, + ] as StatsData[]; + const statsData2 = [ + { + label: intl.formatMessage({ id: 'profile.resource_credits' }), + value: _resourceCredits, + suffix: '%', + }, + { label: intl.formatMessage({ id: 'profile.reputation' }), value: _reputation }, + ] as StatsData[]; - //UI CALLBACKS - - const _openFullProfile = () => { - let params = { - username, - reputation: user ? user.reputation : null - }; - - - RootNavigation.navigate({ - name: ROUTES.SCREENS.PROFILE, - params, - key: username, - }); - - if (onClose) { - onClose(); - } - } - - //extract prop values - let _votingPower = ''; - let _resourceCredits = ''; - let _followerCount = 0; - let _followingCount = 0; - let _postCount = 0; - let _about = ''; - let _reputation = 0; - let _createdData = null; - - if (isProfileLoaded) { - _votingPower = getVotingPower(user).toFixed(1); - _resourceCredits = getRcPower(user).toFixed(0); - _postCount = user.post_count || 0; - _about = user.about?.profile?.about || ''; - _reputation = parseReputation(user.reputation); - _createdData = getTimeFromNowNative(user.created) - - if (follows) { - _followerCount = follows.follower_count || 0; - _followingCount = follows.following_count || 0 - } - } - - - - const statsData1 = [ - { label: intl.formatMessage({ id: 'profile.follower' }), value: _followerCount }, - { label: intl.formatMessage({ id: 'profile.following' }), value: _followingCount }, - { label: intl.formatMessage({ id: 'profile.post' }), value: _postCount }, - ] as StatsData[] - - const statsData2 = [ - { label: intl.formatMessage({ id: 'profile.resource_credits' }), value: _resourceCredits, suffix: '%' }, - { label: intl.formatMessage({ id: 'profile.reputation' }), value: _reputation }, - ] as StatsData[] - - return ( - - - - - - {isLoggedIn && ( - - )} - - - ) + return ( + + + + + + {isLoggedIn && ( + + )} + + ); }; diff --git a/src/components/organisms/quickProfileModal/children/quickProfileStyles.ts b/src/components/organisms/quickProfileModal/children/quickProfileStyles.ts index 2f8fca3e2..d55aacb36 100644 --- a/src/components/organisms/quickProfileModal/children/quickProfileStyles.ts +++ b/src/components/organisms/quickProfileModal/children/quickProfileStyles.ts @@ -3,102 +3,98 @@ import EStyleSheet from 'react-native-extended-stylesheet'; import { getBottomSpace } from 'react-native-iphone-x-helper'; export default EStyleSheet.create({ - modalStyle: { - backgroundColor: '$primaryBackgroundColor', - margin:0, - paddingTop:32, - marginHorizontal:24, - paddingBottom: getBottomSpace() + 8, - }, + modalStyle: { + backgroundColor: '$primaryBackgroundColor', + margin: 0, + paddingTop: 32, + marginHorizontal: 24, + paddingBottom: getBottomSpace() + 8, + }, - sheetContent: { - backgroundColor: '$primaryBackgroundColor', - }, + sheetContent: { + backgroundColor: '$primaryBackgroundColor', + }, - container:{ - alignItems:'center', - marginHorizontal:16 - } as ViewStyle, + container: { + alignItems: 'center', + marginHorizontal: 16, + } as ViewStyle, - image:{ - width:128, - height:128, - borderRadius:64, - backgroundColor: '$primaryGray' - } as ImageStyle, + image: { + width: 128, + height: 128, + borderRadius: 64, + backgroundColor: '$primaryGray', + } as ImageStyle, - textContainer:{ - marginTop:32, - marginBottom:44, - } as ViewStyle, + textContainer: { + marginTop: 32, + marginBottom: 44, + } as ViewStyle, - title: { - color: '$primaryBlack', - alignSelf: 'center', - textAlign: 'center', - fontSize: 18, - fontWeight: 'bold', - marginTop:32, - } as TextStyle, + title: { + color: '$primaryBlack', + alignSelf: 'center', + textAlign: 'center', + fontSize: 18, + fontWeight: 'bold', + marginTop: 32, + } as TextStyle, - statValue: { - fontFamily:'$editorFont', - color: '$primaryBlack', - alignSelf: 'center', - textAlign: 'center', - fontSize: 34, - fontWeight: 'normal', - } as TextStyle, + statValue: { + fontFamily: '$editorFont', + color: '$primaryBlack', + alignSelf: 'center', + textAlign: 'center', + fontSize: 34, + fontWeight: 'normal', + } as TextStyle, - statLabel: { - color: '$primaryBlack', - alignSelf: 'center', - textAlign: 'center', - fontSize: 16, - fontWeight: 'normal', - } as TextStyle, + statLabel: { + color: '$primaryBlack', + alignSelf: 'center', + textAlign: 'center', + fontSize: 16, + fontWeight: 'normal', + } as TextStyle, + bodyText: { + color: '$primaryBlack', + alignSelf: 'center', + textAlign: 'center', + fontSize: 18, + marginTop: 6, + } as TextStyle, - bodyText: { - color: '$primaryBlack', - alignSelf: 'center', - textAlign: 'center', - fontSize: 18, - marginTop:6, - } as TextStyle, + btnText: { + color: '$pureWhite', + } as TextStyle, + button: { + marginTop: 40, + backgroundColor: '$primaryBlue', + paddingHorizontal: 44, + paddingVertical: 16, + borderRadius: 32, + justifyContent: 'center', + alignItems: 'center', + } as ViewStyle, - btnText:{ - color:'$pureWhite' - } as TextStyle, + actionPanel: { + position: 'absolute', + right: 0, + top: 0, + flexDirection: 'row', + alignItems: 'center', + } as ViewStyle, - button:{ - marginTop: 40, - backgroundColor:'$primaryBlue', - paddingHorizontal:44, - paddingVertical:16, - borderRadius:32, - justifyContent:'center', - alignItems:'center' - } as ViewStyle, - - - actionPanel:{ - position: 'absolute', - right:0, - top:0, - flexDirection:'row', - alignItems:'center', - } as ViewStyle, - - progressCircle:{ - position:'absolute', - top:0, - bottom:0, - left:0, - right:0, - alignItems:'center', - justifyContent:'center' - } as ViewStyle - -}) \ No newline at end of file + progressCircle: { + position: 'absolute', + top: 0, + bottom: 0, + left: 0, + right: 0, + alignItems: 'center', + justifyContent: 'center', + } as ViewStyle, +}); diff --git a/src/components/postCard/children/upvoteButton.tsx b/src/components/postCard/children/upvoteButton.tsx index bb6a5e790..fd1015d6a 100644 --- a/src/components/postCard/children/upvoteButton.tsx +++ b/src/components/postCard/children/upvoteButton.tsx @@ -1,123 +1,105 @@ -import React, { Fragment, useCallback, useEffect, useRef, useState } from "react"; -import { findNodeHandle, NativeModules, View, TouchableOpacity, Text, Alert } from "react-native"; -import { useAppSelector } from "../../../hooks"; -import { PulseAnimation } from "../../animations"; +import React, { Fragment, useCallback, useEffect, useRef, useState } from 'react'; +import { findNodeHandle, NativeModules, View, TouchableOpacity, Text, Alert } from 'react-native'; +import { Rect } from 'react-native-modal-popover/lib/PopoverGeometry'; +import { useAppSelector } from '../../../hooks'; +import { PulseAnimation } from '../../animations'; import { isVoted as isVotedFunc, isDownVoted as isDownVotedFunc } from '../../../utils/postParser'; -import Icon from "../../icon"; +import Icon from '../../icon'; import styles from './children.styles'; -import { FormattedCurrency } from "../../formatedElements"; -import { Rect } from "react-native-modal-popover/lib/PopoverGeometry"; -import { PostTypes } from "../../../constants/postTypes"; +import { FormattedCurrency } from '../../formatedElements'; +import { PostTypes } from '../../../constants/postTypes'; interface UpvoteButtonProps { - content: any, - activeVotes: any[], - isShowPayoutValue?: boolean, - boldPayout?: boolean, - parentType?: PostTypes; - onUpvotePress: (anchorRect: Rect, onVotingStart: (status:number)=>void) => void, - onPayoutDetailsPress: (anchorRef: Rect) => void, + content: any; + activeVotes: any[]; + isShowPayoutValue?: boolean; + boldPayout?: boolean; + parentType?: PostTypes; + onUpvotePress: (anchorRect: Rect, onVotingStart: (status: number) => void) => void; + onPayoutDetailsPress: (anchorRef: Rect) => void; } export const UpvoteButton = ({ - content, - activeVotes, - isShowPayoutValue, - boldPayout, - onUpvotePress, - onPayoutDetailsPress + content, + activeVotes, + isShowPayoutValue, + boldPayout, + onUpvotePress, + onPayoutDetailsPress, }: UpvoteButtonProps) => { + const upvoteRef = useRef(null); + const detailsRef = useRef(null); - const upvoteRef = useRef(null); - const detailsRef = useRef(null); + const currentAccount = useAppSelector((state) => state.account.currentAccount); - const currentAccount = useAppSelector((state => state.account.currentAccount)); + const [isVoted, setIsVoted] = useState(null); + const [isDownVoted, setIsDownVoted] = useState(null); - const [isVoted, setIsVoted] = useState(null); - const [isDownVoted, setIsDownVoted] = useState(null); + useEffect(() => { + _calculateVoteStatus(); + }, [activeVotes]); + const _calculateVoteStatus = useCallback(async () => { + // TODO: do this heavy lifting during parsing or react-query/cache response + const _isVoted = await isVotedFunc(activeVotes, currentAccount?.name); + const _isDownVoted = await isDownVotedFunc(activeVotes, currentAccount?.name); - useEffect(() => { + setIsVoted(_isVoted && parseInt(_isVoted, 10) / 10000); + setIsDownVoted(_isDownVoted && (parseInt(_isDownVoted, 10) / 10000) * -1); + }, [activeVotes]); + + const _getRectFromRef = (ref: any, callback: (anchorRect: Rect, onVotingStart?) => void) => { + const handle = findNodeHandle(ref.current); + if (handle) { + NativeModules.UIManager.measure(handle, (x0, y0, width, height, x, y) => { + const anchorRect: Rect = { x, y, width, height }; + callback(anchorRect); + }); + } + }; + + const _onPress = () => { + const _onVotingStart = (status) => { + if (status > 0) { + setIsVoted(true); + } else if (status < 0) { + setIsDownVoted(true); + } else { _calculateVoteStatus(); - }, [activeVotes]); + } + }; + _getRectFromRef(upvoteRef, (rect) => { + onUpvotePress(rect, _onVotingStart); + }); + }; + const _onDetailsPress = () => { + _getRectFromRef(detailsRef, onPayoutDetailsPress); + }; - const _calculateVoteStatus = useCallback(async () => { + const isDeclinedPayout = content?.is_declined_payout; + const totalPayout = content?.total_payout; + const maxPayout = content?.max_payout; - //TODO: do this heavy lifting during parsing or react-query/cache response - const _isVoted = await isVotedFunc(activeVotes, currentAccount?.name); - const _isDownVoted = await isDownVotedFunc(activeVotes, currentAccount?.name); + const payoutLimitHit = totalPayout >= maxPayout; + const _shownPayout = payoutLimitHit && maxPayout > 0 ? maxPayout : totalPayout; - - setIsVoted(_isVoted && parseInt(_isVoted, 10) / 10000); - setIsDownVoted(_isDownVoted && (parseInt(_isDownVoted, 10) / 10000) * -1); - - }, [activeVotes]); + let iconName = 'upcircleo'; + const iconType = 'AntDesign'; + let downVoteIconName = 'downcircleo'; + if (isVoted) { + iconName = 'upcircle'; + } - const _getRectFromRef = (ref: any, callback: (anchorRect: Rect, onVotingStart?) => void) => { - const handle = findNodeHandle(ref.current); - if (handle) { - NativeModules.UIManager.measure(handle, (x0, y0, width, height, x, y) => { - const anchorRect: Rect = { x, y, width, height }; - callback(anchorRect) - }); - } - } + if (isDownVoted) { + downVoteIconName = 'downcircle'; + } - - const _onPress = () => { - const _onVotingStart = (status) => { - if(status > 0){ - setIsVoted(true); - } else if (status < 0) { - setIsDownVoted(true); - } else { - _calculateVoteStatus(); - } - } - _getRectFromRef(upvoteRef, (rect)=>{ - onUpvotePress(rect, _onVotingStart) - }); - } - - const _onDetailsPress = () => { - _getRectFromRef(detailsRef, onPayoutDetailsPress) - } - - - const isDeclinedPayout = content?.is_declined_payout; - const totalPayout = content?.total_payout; - const maxPayout = content?.max_payout; - - const payoutLimitHit = totalPayout >= maxPayout; - const _shownPayout = payoutLimitHit && maxPayout > 0 ? maxPayout : totalPayout; - - - - - let iconName = 'upcircleo'; - const iconType = 'AntDesign'; - let downVoteIconName = 'downcircleo'; - - if (isVoted) { - iconName = 'upcircle'; - } - - if (isDownVoted) { - downVoteIconName = 'downcircle'; - } - - - - return ( - - - {/* + return ( + + + {/* {isVoting ? ( ) : ( */} - - - - {/* )} - */} - - - {isShowPayoutValue && ( - - - {} - - - - )} - + + - - ) -} + {/* )} + */} + + + {isShowPayoutValue && ( + + + + + + )} + + + ); +}; diff --git a/src/components/postComments/children/commentsSection.tsx b/src/components/postComments/children/commentsSection.tsx index 12b6f427e..83ee3d7a4 100644 --- a/src/components/postComments/children/commentsSection.tsx +++ b/src/components/postComments/children/commentsSection.tsx @@ -15,12 +15,15 @@ export const CommentsSection = ({ item, index, revealReplies, ...props }) => { const _renderComment = (item, index = 0) => { // animation makes sure there is 100 ms gab between each comment item - const _enteringAnim = index >= 0 - ? SlideInRight.duration(150).springify().delay(index * 100) - : undefined + const _enteringAnim = + index >= 0 + ? SlideInRight.duration(150) + .springify() + .delay(index * 100) + : undefined; return ( - + { @@ -63,7 +65,7 @@ const PostComments = forwardRef( const postsCachePrimer = postQueries.usePostsCachePrimer(); const writeCommentRef = useRef(null); - const postInteractionRef = useRef(null); + const postInteractionRef = useRef(null); const commentsListRef = useRef | null>(null); const [selectedFilter, setSelectedFilter] = useState('trending'); @@ -72,7 +74,6 @@ const PostComments = forwardRef( const [refreshing, setRefreshing] = useState(false); - const sortedSections = useMemo( () => sortComments(selectedFilter, discussionQuery.sectionedData), [discussionQuery.sectionedData, selectedFilter], @@ -107,9 +108,6 @@ const PostComments = forwardRef( onRefresh(); }; - - - const _handleOnDropdownSelect = (option, index) => { setSelectedFilter(option); setSelectedOptionIndex(index); @@ -139,7 +137,6 @@ const PostComments = forwardRef( }; const _handleDeleteComment = (_permlink) => { - const _onConfirmDelete = async () => { try { await deleteComment(currentAccount, pinHash, _permlink); @@ -154,23 +151,27 @@ const PostComments = forwardRef( dispatch(updateCommentCache(_commentPath, _deletedItem, { isUpdate: true })); } } catch (err) { - console.warn('Failed to delete comment') + console.warn('Failed to delete comment'); } + }; - } - - dispatch(showActionModal({ - title: intl.formatMessage({ id: 'delete.confirm_delete_title' }), - buttons: [{ - text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => { console.log("canceled delete comment") } - }, { - text: intl.formatMessage({ id: 'alert.delete' }), - onPress: _onConfirmDelete - }] - })) - - + dispatch( + showActionModal({ + title: intl.formatMessage({ id: 'delete.confirm_delete_title' }), + buttons: [ + { + text: intl.formatMessage({ id: 'alert.cancel' }), + onPress: () => { + console.log('canceled delete comment'); + }, + }, + { + text: intl.formatMessage({ id: 'alert.delete' }), + onPress: _onConfirmDelete, + }, + ], + }), + ); }; const _openReplyThread = (comment) => { @@ -187,7 +188,7 @@ const PostComments = forwardRef( const _handleOnUserPress = (username) => { dispatch(showProfileModal(username)); - } + }; const _handleShowOptionsMenu = (comment) => { const _showCopiedToast = () => { @@ -231,11 +232,6 @@ const PostComments = forwardRef( ); }; - - - - - const _onContentSizeChange = (x: number, y: number) => { // update header height if (y !== headerHeight) { @@ -243,8 +239,6 @@ const PostComments = forwardRef( } }; - - const _postContentView = ( <> {postContentView && postContentView} @@ -263,8 +257,7 @@ const PostComments = forwardRef( ); const _renderEmptyContent = () => { - - if(isPostLoading){ + if (isPostLoading) { return null; } @@ -303,10 +296,8 @@ const PostComments = forwardRef( openReplyThread={_openReplyThread} onUpvotePress={(args) => onUpvotePress({ ...args, postType: PostTypes.COMMENT })} /> - ) - } - - + ); + }; return ( @@ -333,14 +324,10 @@ const PostComments = forwardRef( } overScrollMode="never" /> - + - ); }, ); export default PostComments; - diff --git a/src/components/postElements/body/view/commentBodyView.tsx b/src/components/postElements/body/view/commentBodyView.tsx index ce4be5746..a177f08f6 100644 --- a/src/components/postElements/body/view/commentBodyView.tsx +++ b/src/components/postElements/body/view/commentBodyView.tsx @@ -101,7 +101,6 @@ const CommentBody = ({ } }; - const _handleOnUserPress = (username) => { if (handleOnUserPress) { handleOnUserPress(username); diff --git a/src/components/postHtmlRenderer/postHtmlRenderer.tsx b/src/components/postHtmlRenderer/postHtmlRenderer.tsx index 7aba32085..6881e151f 100644 --- a/src/components/postHtmlRenderer/postHtmlRenderer.tsx +++ b/src/components/postHtmlRenderer/postHtmlRenderer.tsx @@ -50,7 +50,7 @@ export const PostHtmlRenderer = memo( body = body .replace(/
/g, '
') .replace(/<\/center>/g, '
') - .replace(//g, '') //TODO: later handle span with propties lie and remove on raw + .replace(//g, '') // TODO: later handle span with propties lie and remove on raw .replace(/<\/span>/g, ''); const _minTableColWidth = contentWidth / 3 - 12; @@ -277,7 +277,6 @@ export const PostHtmlRenderer = memo( const _paraRenderer = ({ TDefaultRenderer, ...props }: CustomRendererProps) => { props.style = props.tnode.parent.tagName === 'li' ? styles.pLi : styles.p; props.onPress = !props.onPress && handleOnContentPress ? handleOnContentPress : props.onPress; - return ; }; @@ -399,7 +398,7 @@ export const PostHtmlRenderer = memo( customHTMLElementModels={customHTMLElementModels} renderersProps={renderersProps} WebView={WebView} - pressableHightlightColor={'transparent'} + pressableHightlightColor="transparent" /> ); }, diff --git a/src/components/postHtmlRenderer/postHtmlRendererStyles.ts b/src/components/postHtmlRenderer/postHtmlRendererStyles.ts index a9b5de106..668fecdbc 100644 --- a/src/components/postHtmlRenderer/postHtmlRendererStyles.ts +++ b/src/components/postHtmlRenderer/postHtmlRendererStyles.ts @@ -87,7 +87,7 @@ export default EStyleSheet.create({ color: '$primaryRed', } as TextStyle, textJustify: { - textAlign: Platform.select({ ios: 'justify', android: 'auto' }), //justify with selectable on android causes ends of text getting clipped, + textAlign: Platform.select({ ios: 'justify', android: 'auto' }), // justify with selectable on android causes ends of text getting clipped, letterSpacing: 0, } as TextStyle, revealButton: { diff --git a/src/components/postHtmlRenderer/postInteractionHandler.tsx b/src/components/postHtmlRenderer/postInteractionHandler.tsx index 57c423e16..a07119f93 100644 --- a/src/components/postHtmlRenderer/postInteractionHandler.tsx +++ b/src/components/postHtmlRenderer/postInteractionHandler.tsx @@ -1,10 +1,4 @@ -import React, { - forwardRef, - useImperativeHandle, - useRef, - useState, - Fragment, -} from 'react'; +import React, { forwardRef, useImperativeHandle, useRef, useState, Fragment } from 'react'; import { PermissionsAndroid, Platform, SafeAreaView, View, Text } from 'react-native'; import { useIntl } from 'react-intl'; import ActionsSheet from 'react-native-actions-sheet'; @@ -12,29 +6,27 @@ import ImageView from 'react-native-image-viewing'; // Components import EStyleSheet from 'react-native-extended-stylesheet'; +import CameraRoll from '@react-native-community/cameraroll'; +import RNFetchBlob from 'rn-fetch-blob'; +import { useDispatch } from 'react-redux'; +import { useNavigation } from '@react-navigation/native'; import ROUTES from '../../constants/routeNames'; import { toastNotification } from '../../redux/actions/uiAction'; import { writeToClipboard } from '../../utils/clipboard'; -import CameraRoll from '@react-native-community/cameraroll'; -import RNFetchBlob from 'rn-fetch-blob'; import { OptionsModal } from '../atoms'; import VideoPlayer from '../videoPlayer/videoPlayerView'; -import { useDispatch } from 'react-redux'; -import { useNavigation } from '@react-navigation/native'; import { IconButton } from '../buttons'; -import styles from './postHtmlRendererStyles' +import styles from './postHtmlRendererStyles'; import { PostTypes } from '../../constants/postTypes'; interface PostHtmlInteractionHandlerProps { - postType?:PostTypes + postType?: PostTypes; } -export const PostHtmlInteractionHandler = forwardRef(({ - postType -}:PostHtmlInteractionHandlerProps, ref) => { - +export const PostHtmlInteractionHandler = forwardRef( + ({ postType }: PostHtmlInteractionHandlerProps, ref) => { const navigation = useNavigation(); const dispatch = useDispatch(); const intl = useIntl(); @@ -52,245 +44,240 @@ export const PostHtmlInteractionHandler = forwardRef(({ const [selectedImage, setSelectedImage] = useState(null); const [selectedLink, setSelectedLink] = useState(null); - - useImperativeHandle(ref, () => ({ - handleImagePress: (url: string, postImgUrls: string[]) => { - setPostImages(postImgUrls); - setSelectedImage(url); - if(postType === PostTypes.WAVE){ - setIsImageModalOpen(true); - } else { - actionImage.current?.show(); - } - - }, - handleLinkPress: (url: string) => { - setSelectedLink(url); - actionLink.current?.show(); - }, - handleYoutubePress: (videoId, startTime) => { - if (videoId && youtubePlayerRef.current) { - setYoutubeVideoId(videoId); - setVideoStartTime(startTime); - youtubePlayerRef.current.setModalVisible(true); - } - }, - - handleVideoPress: (embedUrl) => { - if (embedUrl && youtubePlayerRef.current) { - setVideoUrl(embedUrl); - setVideoStartTime(0); - youtubePlayerRef.current.setModalVisible(true); - } + handleImagePress: (url: string, postImgUrls: string[]) => { + setPostImages(postImgUrls); + setSelectedImage(url); + if (postType === PostTypes.WAVE) { + setIsImageModalOpen(true); + } else { + actionImage.current?.show(); } - })) - + }, + handleLinkPress: (url: string) => { + setSelectedLink(url); + actionLink.current?.show(); + }, + handleYoutubePress: (videoId, startTime) => { + if (videoId && youtubePlayerRef.current) { + setYoutubeVideoId(videoId); + setVideoStartTime(startTime); + youtubePlayerRef.current.setModalVisible(true); + } + }, + handleVideoPress: (embedUrl) => { + if (embedUrl && youtubePlayerRef.current) { + setVideoUrl(embedUrl); + setVideoStartTime(0); + youtubePlayerRef.current.setModalVisible(true); + } + }, + })); const checkAndroidPermission = async () => { - try { - const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE; - await PermissionsAndroid.request(permission); - Promise.resolve(); - } catch (error) { - Promise.reject(error); - } + try { + const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE; + await PermissionsAndroid.request(permission); + Promise.resolve(); + } catch (error) { + Promise.reject(error); + } }; const _downloadImage = async (uri) => { - return RNFetchBlob.config({ - fileCache: true, - appendExt: 'jpg', - }) - .fetch('GET', uri) - .then((res) => { - const { status } = res.info(); + return RNFetchBlob.config({ + fileCache: true, + appendExt: 'jpg', + }) + .fetch('GET', uri) + .then((res) => { + const { status } = res.info(); - if (status == 200) { - return res.path(); - } else { - Promise.reject(); - } - }) - .catch((errorMessage) => { - Promise.reject(errorMessage); - }); + if (status == 200) { + return res.path(); + } else { + Promise.reject(); + } + }) + .catch((errorMessage) => { + Promise.reject(errorMessage); + }); }; const _saveImage = async (uri) => { - try { - if (Platform.OS === 'android') { - await checkAndroidPermission(); - uri = `file://${await _downloadImage(uri)}`; - } - CameraRoll.saveToCameraRoll(uri) - .then(() => { - dispatch( - toastNotification( - intl.formatMessage({ - id: 'post.image_saved', - }), - ), - ); - }) - .catch(() => { - dispatch( - toastNotification( - intl.formatMessage({ - id: 'post.image_saved_error', - }), - ), - ); - }); - } catch (error) { - dispatch( - toastNotification( - intl.formatMessage({ - id: 'post.image_saved_error', - }), - ), - ); + try { + if (Platform.OS === 'android') { + await checkAndroidPermission(); + uri = `file://${await _downloadImage(uri)}`; } + CameraRoll.saveToCameraRoll(uri) + .then(() => { + dispatch( + toastNotification( + intl.formatMessage({ + id: 'post.image_saved', + }), + ), + ); + }) + .catch(() => { + dispatch( + toastNotification( + intl.formatMessage({ + id: 'post.image_saved_error', + }), + ), + ); + }); + } catch (error) { + dispatch( + toastNotification( + intl.formatMessage({ + id: 'post.image_saved_error', + }), + ), + ); + } }; const _handleImageOptionPress = (ind) => { - if (ind === 1) { - // open gallery mode - setIsImageModalOpen(true); - } - if (ind === 0) { - // copy to clipboard - writeToClipboard(selectedImage).then(() => { - dispatch( - toastNotification( - intl.formatMessage({ - id: 'alert.copied', - }), - ), - ); - }); - } - if (ind === 2) { - // save to local - _saveImage(selectedImage); - } + if (ind === 1) { + // open gallery mode + setIsImageModalOpen(true); + } + if (ind === 0) { + // copy to clipboard + writeToClipboard(selectedImage).then(() => { + dispatch( + toastNotification( + intl.formatMessage({ + id: 'alert.copied', + }), + ), + ); + }); + } + if (ind === 2) { + // save to local + _saveImage(selectedImage); + } - setSelectedImage(null); + setSelectedImage(null); }; const _handleLinkOptionPress = (ind) => { - if (ind === 1) { - // open link - if (selectedLink) { - navigation.navigate({ - name: ROUTES.SCREENS.WEB_BROWSER, - params: { - url: selectedLink, - }, - key: selectedLink, - } as never); - } - } - if (ind === 0) { - // copy to clipboard - writeToClipboard(selectedLink).then(() => { - dispatch( - toastNotification( - intl.formatMessage({ - id: 'alert.copied', - }), - ), - ); - }); + if (ind === 1) { + // open link + if (selectedLink) { + navigation.navigate({ + name: ROUTES.SCREENS.WEB_BROWSER, + params: { + url: selectedLink, + }, + key: selectedLink, + } as never); } + } + if (ind === 0) { + // copy to clipboard + writeToClipboard(selectedLink).then(() => { + dispatch( + toastNotification( + intl.formatMessage({ + id: 'alert.copied', + }), + ), + ); + }); + } - setSelectedLink(null); + setSelectedLink(null); }; const _renderImageViewerHeader = (imageIndex) => { - return ( - - - {`${imageIndex + 1}/${ - postImages.length - }`} - setIsImageModalOpen(false)} - /> - - - ); + return ( + + + {`${imageIndex + 1}/${ + postImages.length + }`} + setIsImageModalOpen(false)} + /> + + + ); }; - + return ( - - ({ uri: url }))} - imageIndex={0} - visible={isImageModalOpen} - animationType="slide" - swipeToCloseEnabled - onRequestClose={() => setIsImageModalOpen(false)} - HeaderComponent={(imageIndex) => _renderImageViewerHeader(imageIndex.imageIndex)} - /> + + ({ uri: url }))} + imageIndex={0} + visible={isImageModalOpen} + animationType="slide" + swipeToCloseEnabled + onRequestClose={() => setIsImageModalOpen(false)} + HeaderComponent={(imageIndex) => _renderImageViewerHeader(imageIndex.imageIndex)} + /> - { - _handleImageOptionPress(index); - }} - /> + { + _handleImageOptionPress(index); + }} + /> + { + _handleLinkOptionPress(index); + }} + /> - { - _handleLinkOptionPress(index); - }} - /> - - { - setYoutubeVideoId(null); - setVideoUrl(null); - }} - > - - - - ) -}) + { + setYoutubeVideoId(null); + setVideoUrl(null); + }} + > + + + + ); + }, +); diff --git a/src/components/postView/view/postDisplayStyles.js b/src/components/postView/view/postDisplayStyles.js index 2858cbab1..341f7b42d 100644 --- a/src/components/postView/view/postDisplayStyles.js +++ b/src/components/postView/view/postDisplayStyles.js @@ -15,7 +15,7 @@ export default EStyleSheet.create({ marginTop: -4, marginBottom: 4, }, - titlePlaceholder:{ + titlePlaceholder: { marginBottom: 4, }, title: { diff --git a/src/components/postView/view/postDisplayView.tsx b/src/components/postView/view/postDisplayView.tsx index 9b8f4b381..71a0f61d8 100644 --- a/src/components/postView/view/postDisplayView.tsx +++ b/src/components/postView/view/postDisplayView.tsx @@ -110,11 +110,7 @@ const PostDisplayView = ({ content, onVotingStart, showPayoutDetails = false, - postType = isWavePost - ? PostTypes.WAVE - : parentPost - ? PostTypes.COMMENT - : PostTypes.POST + postType = isWavePost ? PostTypes.WAVE : parentPost ? PostTypes.COMMENT : PostTypes.POST, }: any) => { if (upvotePopoverRef.current) { upvotePopoverRef.current.showPopover({ @@ -236,7 +232,7 @@ const PostDisplayView = ({ // show quick reply modal const _showQuickReplyModal = (_post = post) => { if (isLoggedIn) { - dispatch(showReplyModal({mode:'comment', parentPost:_post})); + dispatch(showReplyModal({ mode: 'comment', parentPost: _post })); } else { console.log('Not LoggedIn'); } @@ -253,7 +249,6 @@ const PostDisplayView = ({ setIsLoadedComments(true); }; - const _postContentView = ( <> {parentPost && } @@ -267,12 +262,11 @@ const PostDisplayView = ({ setPostBodyHeight(event.nativeEvent.layout.height); }} > - - { - !!post.title && !post.depth - ? {post.title} - : - } + {!!post.title && !post.depth ? ( + {post.title} + ) : ( + + )} - + )} diff --git a/src/components/postsList/container/postsListContainer.tsx b/src/components/postsList/container/postsListContainer.tsx index 5ca18d79e..261db12cb 100644 --- a/src/components/postsList/container/postsListContainer.tsx +++ b/src/components/postsList/container/postsListContainer.tsx @@ -7,13 +7,7 @@ import React, { Fragment, useMemo, } from 'react'; -import { - FlatListProps, - FlatList, - RefreshControl, - ActivityIndicator, - View, -} from 'react-native'; +import { FlatListProps, FlatList, RefreshControl, ActivityIndicator, View } from 'react-native'; import { FlashList } from '@shopify/flash-list'; import { useSelector } from 'react-redux'; import { useNavigation } from '@react-navigation/native'; diff --git a/src/components/qrModal/qrModalStyles.ts b/src/components/qrModal/qrModalStyles.ts index 5ce8675fa..e5f40dc7c 100644 --- a/src/components/qrModal/qrModalStyles.ts +++ b/src/components/qrModal/qrModalStyles.ts @@ -1,6 +1,7 @@ import { TextStyle, ViewStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; import getWindowDimensions from '../../utils/getWindowDimensions'; + const { width: SCREEN_WIDTH } = getWindowDimensions(); export default EStyleSheet.create({ diff --git a/src/components/qrModal/qrModalView.tsx b/src/components/qrModal/qrModalView.tsx index 47536a903..adabb7912 100644 --- a/src/components/qrModal/qrModalView.tsx +++ b/src/components/qrModal/qrModalView.tsx @@ -5,6 +5,7 @@ import EStyleSheet from 'react-native-extended-stylesheet'; import QRCodeScanner from 'react-native-qrcode-scanner'; import { useIntl } from 'react-intl'; import { check, request, PERMISSIONS, RESULTS, openSettings } from 'react-native-permissions'; +import { get } from 'lodash'; import styles from './qrModalStyles'; import { useAppDispatch, useAppSelector } from '../../hooks'; import { @@ -19,13 +20,13 @@ import getWindowDimensions from '../../utils/getWindowDimensions'; import { isHiveUri, getFormattedTx } from '../../utils/hive-uri'; import { handleHiveUriOperation, resolveTransaction } from '../../providers/hive/dhive'; import bugsnagInstance from '../../config/bugsnag'; -import { get } from 'lodash'; import showLoginAlert from '../../utils/showLoginAlert'; import authType from '../../constants/authType'; import { delay } from '../../utils/editor'; -import ROUTES from '../../../src/constants/routeNames'; +import ROUTES from '../../constants/routeNames'; const hiveuri = require('hive-uri'); + const screenHeight = getWindowDimensions().height; interface QRModalProps {} @@ -149,7 +150,7 @@ export const QRModal = ({}: QRModalProps) => { await delay(500); // NOTE: it's required to avoid modal mis fire dispatch( showWebViewModal({ - uri: uri, + uri, }), ); return; @@ -157,10 +158,10 @@ export const QRModal = ({}: QRModalProps) => { const parsed = hiveuri.decode(uri); const authoritiesMap = new Map(); - authoritiesMap.set('active', currentAccount?.local?.activeKey ? true : false); - authoritiesMap.set('posting', currentAccount?.local?.postingKey ? true : false); - authoritiesMap.set('owner', currentAccount?.local?.ownerKey ? true : false); - authoritiesMap.set('memo', currentAccount?.local?.memoKey ? true : false); + authoritiesMap.set('active', !!currentAccount?.local?.activeKey); + authoritiesMap.set('posting', !!currentAccount?.local?.postingKey); + authoritiesMap.set('owner', !!currentAccount?.local?.ownerKey); + authoritiesMap.set('memo', !!currentAccount?.local?.memoKey); getFormattedTx(parsed.tx, authoritiesMap) .then(async (formattedTx) => { @@ -218,7 +219,6 @@ export const QRModal = ({}: QRModalProps) => { { key: errObj.authorityKeyType }, ), ); - return; }); }; diff --git a/src/components/quickReplyModal/quickReplyModalContent.tsx b/src/components/quickReplyModal/quickReplyModalContent.tsx index 344608d8f..2829481b4 100644 --- a/src/components/quickReplyModal/quickReplyModalContent.tsx +++ b/src/components/quickReplyModal/quickReplyModalContent.tsx @@ -9,25 +9,24 @@ import React, { useMemo, } from 'react'; import EStyleSheet from 'react-native-extended-stylesheet'; -import { - View, - Text, - TouchableOpacity, - Keyboard, - Platform, - ActivityIndicator, -} from 'react-native'; +import { View, Text, TouchableOpacity, Keyboard, Platform, ActivityIndicator } from 'react-native'; import { useIntl } from 'react-intl'; import { useSelector, useDispatch } from 'react-redux'; import { get, debounce } from 'lodash'; import { postBodySummary } from '@ecency/render-helper'; +import FastImage from 'react-native-fast-image'; import styles from './quickReplyModalStyles'; -import { Icon, IconButton, MainButton, TextButton, TextInput, UploadsGalleryModal, UserAvatar } from '..'; -import { delay } from '../../utils/editor'; import { - deleteDraftCacheEntry, - updateDraftCache, -} from '../../redux/actions/cacheActions'; + Icon, + IconButton, + MainButton, + TextButton, + TextInput, + UploadsGalleryModal, + UserAvatar, +} from '..'; +import { delay } from '../../utils/editor'; +import { deleteDraftCacheEntry, updateDraftCache } from '../../redux/actions/cacheActions'; import { default as ROUTES } from '../../constants/routeNames'; import RootNavigation from '../../navigation/rootNavigation'; import { Draft } from '../../redux/reducers/cacheReducer'; @@ -35,11 +34,13 @@ import { RootState } from '../../redux/store/store'; import { postQueries } from '../../providers/queries'; import { usePostSubmitter } from './usePostSubmitter'; -import { MediaInsertData, MediaInsertStatus } from '../uploadsGalleryModal/container/uploadsGalleryModal'; -import FastImage from 'react-native-fast-image'; +import { + MediaInsertData, + MediaInsertStatus, +} from '../uploadsGalleryModal/container/uploadsGalleryModal'; export interface QuickReplyModalContentProps { - mode: 'comment' | 'wave' | 'post', + mode: 'comment' | 'wave' | 'post'; selectedPost?: any; handleCloseRef?: any; onClose: () => void; @@ -48,17 +49,12 @@ export interface QuickReplyModalContentProps { const MAX_BODY_LENGTH = 250; export const QuickReplyModalContent = forwardRef( - ({ - mode, - selectedPost, - onClose - }: QuickReplyModalContentProps, ref) => { + ({ mode, selectedPost, onClose }: QuickReplyModalContentProps, ref) => { const intl = useIntl(); const dispatch = useDispatch(); const uploadsGalleryModalRef = useRef(null); - const postsCachePrimer = postQueries.usePostsCachePrimer(); const postSubmitter = usePostSubmitter(); @@ -76,19 +72,20 @@ export const QuickReplyModalContent = forwardRef( const parentAuthor = selectedPost ? selectedPost.author : ''; const parentPermlink = selectedPost ? selectedPost.permlink : ''; + const headerText = + mode === 'wave' + ? intl.formatMessage({ id: 'quick_reply.summary_wave' }, { host: 'ecency.waves' }) // TODO: update based on selected host + : selectedPost && (selectedPost.summary || postBodySummary(selectedPost, 150, Platform.OS)); - const headerText = mode === 'wave' - ? intl.formatMessage({ id: 'quick_reply.summary_wave' }, { host: 'ecency.waves' }) //TODO: update based on selected host - : selectedPost && (selectedPost.summary || postBodySummary(selectedPost, 150, Platform.OS)); - - const draftId = mode === 'wave' - ? `${currentAccount.name}/ecency.waves` //TODO: update author based on selected host - : `${currentAccount.name}/${parentAuthor}/${parentPermlink}`; // different draftId for each user acount - + const draftId = + mode === 'wave' + ? `${currentAccount.name}/ecency.waves` // TODO: update author based on selected host + : `${currentAccount.name}/${parentAuthor}/${parentPermlink}`; // different draftId for each user acount const bodyLengthExceeded = useMemo( - () => commentValue.length > MAX_BODY_LENGTH && mode === 'wave', - [commentValue, mode]); + () => commentValue.length > MAX_BODY_LENGTH && mode === 'wave', + [commentValue, mode], + ); useImperativeHandle(ref, () => ({ handleSheetClose() { @@ -112,7 +109,6 @@ export const QuickReplyModalContent = forwardRef( } setCommentValue(_value); - }, [selectedPost]); // add quick comment value into cache @@ -146,29 +142,24 @@ export const QuickReplyModalContent = forwardRef( }); }; - - - // handle submit reply const _submitPost = async () => { - let _isSuccess = false; - let _body = mediaUrls.length > 0 ? commentValue + `\n\n ![Wave Media](${mediaUrls[0]})` : commentValue; + const _body = + mediaUrls.length > 0 ? `${commentValue}\n\n ![Wave Media](${mediaUrls[0]})` : commentValue; switch (mode) { case 'comment': _isSuccess = await postSubmitter.submitReply(_body, selectedPost); - break;; + break; case 'wave': _isSuccess = await postSubmitter.submitWave(_body); break; default: - throw new Error("mode needs implementing") + throw new Error('mode needs implementing'); } - if (_isSuccess) { - // delete quick comment draft cache if it exist if (draftsCollection && draftsCollection[draftId]) { dispatch(deleteDraftCacheEntry(draftId)); @@ -178,13 +169,10 @@ export const QuickReplyModalContent = forwardRef( } else { _addQuickCommentIntoCache(); // add comment value into cache if there is error while posting comment } - }; - - const _handleMediaInsert = (data: MediaInsertData[]) => { - const _insertUrls: string[] = [] + const _insertUrls: string[] = []; const _item = data[0]; @@ -192,7 +180,7 @@ export const QuickReplyModalContent = forwardRef( switch (_item.status) { case MediaInsertStatus.READY: if (_item.url) { - _insertUrls.push(_item.url) + _insertUrls.push(_item.url); } break; case MediaInsertStatus.FAILED: @@ -201,14 +189,10 @@ export const QuickReplyModalContent = forwardRef( } } - setMediaModalVisible(false); uploadsGalleryModalRef.current?.toggleModal(false); setMediaUrls(_insertUrls); - - } - - + }; const _handleExpandBtn = async () => { if (selectedPost) { @@ -228,10 +212,10 @@ export const QuickReplyModalContent = forwardRef( const _handleMediaBtn = () => { if (uploadsGalleryModalRef.current) { - uploadsGalleryModalRef.current.toggleModal(!mediaModalVisible) - setMediaModalVisible(!mediaModalVisible) + uploadsGalleryModalRef.current.toggleModal(!mediaModalVisible); + setMediaModalVisible(!mediaModalVisible); } - } + }; const _deboucedCacheUpdate = useCallback(debounce(_addQuickCommentIntoCache, 500), []); @@ -240,9 +224,6 @@ export const QuickReplyModalContent = forwardRef( _deboucedCacheUpdate(value); }; - - - // VIEW_RENDERERS const _renderSummary = () => ( @@ -253,8 +234,6 @@ export const QuickReplyModalContent = forwardRef( ); - - const _renderAvatar = () => ( @@ -264,14 +243,12 @@ export const QuickReplyModalContent = forwardRef( ); - const _renderMediaPanel = () => { const _onPress = () => { - setMediaUrls([]) - } + setMediaUrls([]); + }; - const _minusIcon = ( - !isUploading && + const _minusIcon = !isUploading && ( - ) + ); + const _mediaThumb = !mediaModalVisible && mediaUrls.length > 0 && ( + + + {_minusIcon} + + ); - const _mediaThumb = ( - !mediaModalVisible && mediaUrls.length > 0 && ( - - - {_minusIcon} - - ) - ) - - const _uploadingPlaceholder = ( - isUploading && + const _uploadingPlaceholder = isUploading && ( + - ) + ); - return - {_mediaThumb} - {_uploadingPlaceholder} - - { - setMediaModalVisible(false); - }} - handleMediaInsert={_handleMediaInsert} - setIsUploading={setIsUploading} - /> - - } + return ( + + {_mediaThumb} + {_uploadingPlaceholder} + { + setMediaModalVisible(false); + }} + handleMediaInsert={_handleMediaInsert} + setIsUploading={setIsUploading} + /> + + ); + }; const _renderExpandBtn = () => { - const _lengthTextStyle = { ...styles.toolbarSpacer, - color: EStyleSheet.value(bodyLengthExceeded ? '$primaryRed' : '$iconColor') - } + color: EStyleSheet.value(bodyLengthExceeded ? '$primaryRed' : '$iconColor'), + }; return ( @@ -346,16 +317,11 @@ export const QuickReplyModalContent = forwardRef( color={EStyleSheet.value('$primaryBlack')} /> ) : ( - - {`${commentValue.length}/${MAX_BODY_LENGTH}`} - + {`${commentValue.length}/${MAX_BODY_LENGTH}`} )} - ); - } - - + }; const _renderReplyBtn = () => { const _titleId = mode !== 'comment' ? 'quick_reply.publish' : 'quick_reply.reply'; @@ -378,13 +344,11 @@ export const QuickReplyModalContent = forwardRef( isLoading={postSubmitter.isSending} /> - ) - + ); }; - - - const _placeholderId = mode === 'comment' ? 'quick_reply.placeholder' : 'quick_reply.placeholder_wave' + const _placeholderId = + mode === 'comment' ? 'quick_reply.placeholder' : 'quick_reply.placeholder_wave'; return ( @@ -409,14 +373,11 @@ export const QuickReplyModalContent = forwardRef( {_renderMediaPanel()} - - - {_renderExpandBtn()} {_renderReplyBtn()} - ) + ); }, ); diff --git a/src/components/quickReplyModal/quickReplyModalStyles.ts b/src/components/quickReplyModal/quickReplyModalStyles.ts index cca49c166..dab9237e7 100644 --- a/src/components/quickReplyModal/quickReplyModalStyles.ts +++ b/src/components/quickReplyModal/quickReplyModalStyles.ts @@ -108,8 +108,8 @@ export default EStyleSheet.create({ width: 96, borderRadius: 16, backgroundColor: '$primaryLightBackground', - justifyContent:'center', - alignItems:'center' + justifyContent: 'center', + alignItems: 'center', } as ImageStyle, minusContainer: { position: 'absolute', @@ -119,12 +119,11 @@ export default EStyleSheet.create({ borderRadius: 16, padding: 2, } as ViewStyle, - toolbarContainer:{ - flexDirection:'row', - alignItems:'center' + toolbarContainer: { + flexDirection: 'row', + alignItems: 'center', } as ViewStyle, - toolbarSpacer:{ - marginLeft:8 + toolbarSpacer: { + marginLeft: 8, } as ViewStyle, - }); diff --git a/src/components/quickReplyModal/quickReplyModalView.tsx b/src/components/quickReplyModal/quickReplyModalView.tsx index 61e45f7a9..26f4c0c15 100644 --- a/src/components/quickReplyModal/quickReplyModalView.tsx +++ b/src/components/quickReplyModal/quickReplyModalView.tsx @@ -9,7 +9,7 @@ const QuickReplyModal = () => { const dispatch = useAppDispatch(); const replyModalVisible = useAppSelector((state) => state.ui.replyModalVisible); - const replyModalData:PostEditorModalData = useAppSelector((state) => state.ui.replyModalData); + const replyModalData: PostEditorModalData = useAppSelector((state) => state.ui.replyModalData); const modalContentRef = useRef(null); const _onClose = () => { diff --git a/src/components/quickReplyModal/usePostSubmitter.ts b/src/components/quickReplyModal/usePostSubmitter.ts index a89292b11..65e302c28 100644 --- a/src/components/quickReplyModal/usePostSubmitter.ts +++ b/src/components/quickReplyModal/usePostSubmitter.ts @@ -1,172 +1,155 @@ -import { useDispatch } from "react-redux"; -import { useAppSelector } from "../../hooks"; -import { postComment } from "../../providers/hive/dhive"; -import { extractMetadata, generateUniquePermlink, makeJsonMetadata } from "../../utils/editor"; -import { Alert } from "react-native"; -import { updateCommentCache } from "../../redux/actions/cacheActions"; -import { toastNotification } from "../../redux/actions/uiAction"; -import { useIntl } from "react-intl"; -import { useState } from "react"; -import { useUserActivityMutation, wavesQueries } from "../../providers/queries"; -import { PointActivityIds } from "../../providers/ecency/ecency.types"; -import { usePublishWaveMutation } from "../../providers/queries/postQueries/wavesQueries"; -import { PostTypes } from "../../constants/postTypes"; - +import { useDispatch } from 'react-redux'; +import { Alert } from 'react-native'; +import { useIntl } from 'react-intl'; +import { useState } from 'react'; +import { useAppSelector } from '../../hooks'; +import { postComment } from '../../providers/hive/dhive'; +import { extractMetadata, generateUniquePermlink, makeJsonMetadata } from '../../utils/editor'; +import { updateCommentCache } from '../../redux/actions/cacheActions'; +import { toastNotification } from '../../redux/actions/uiAction'; +import { useUserActivityMutation, wavesQueries } from '../../providers/queries'; +import { PointActivityIds } from '../../providers/ecency/ecency.types'; +import { usePublishWaveMutation } from '../../providers/queries/postQueries/wavesQueries'; +import { PostTypes } from '../../constants/postTypes'; export const usePostSubmitter = () => { + const dispatch = useDispatch(); + const intl = useIntl(); - const dispatch = useDispatch(); - const intl = useIntl(); + const pusblishWaveMutation = usePublishWaveMutation(); - const pusblishWaveMutation = usePublishWaveMutation(); + const currentAccount = useAppSelector((state) => state.account.currentAccount); + const pinCode = useAppSelector((state) => state.application.pin); + const userActivityMutation = useUserActivityMutation(); + const [isSending, setIsSending] = useState(false); + // handle submit reply + const _submitReply = async ( + commentBody: string, + parentPost: any, + postType: PostTypes = PostTypes.COMMENT, + ) => { + if (!commentBody) { + return false; + } + if (isSending) { + return false; + } - const currentAccount = useAppSelector((state) => state.account.currentAccount); - const pinCode = useAppSelector(state => state.application.pin); - const userActivityMutation = useUserActivityMutation(); - const [isSending, setIsSending] = useState(false); + if (currentAccount) { + setIsSending(true); + const _prefix = + postType === PostTypes.WAVE ? postType : `re-${parentPost.author.replace(/\./g, '')}`; + const permlink = generateUniquePermlink(_prefix); - // handle submit reply - const _submitReply = async (commentBody: string, parentPost: any, postType: PostTypes = PostTypes.COMMENT) => { - if (!commentBody) { - return false; - } - if (isSending) { - return false; - } + const author = currentAccount.name; + const parentAuthor = parentPost.author; + const parentPermlink = parentPost.permlink; + const parentTags = parentPost.json_metadata.tags; + const category = parentPost.category || ''; + const url = `/${category}/@${parentAuthor}/${parentPermlink}#@${author}/${permlink}`; - if (currentAccount) { - setIsSending(true); + // adding jsonmeta with image ratios here.... + const meta = await extractMetadata({ + body: commentBody, + fetchRatios: true, + postType, + }); + const jsonMetadata = makeJsonMetadata(meta, parentTags || ['ecency']); - const _prefix = postType === PostTypes.WAVE - ? postType - : `re-${parentPost.author.replace(/\./g, '')}` - const permlink = generateUniquePermlink(_prefix); + console.log( + currentAccount, + pinCode, + parentAuthor, + parentPermlink, + permlink, + commentBody, + jsonMetadata, + ); - const author = currentAccount.name; - const parentAuthor = parentPost.author; - const parentPermlink = parentPost.permlink; - const parentTags = parentPost.json_metadata.tags; - const category = parentPost.category || ''; - const url = `/${category}/@${parentAuthor}/${parentPermlink}#@${author}/${permlink}`; + try { + const response = await postComment( + currentAccount, + pinCode, + parentAuthor, + parentPermlink, + permlink, + commentBody, + jsonMetadata, + ); - //adding jsonmeta with image ratios here.... - const meta = await extractMetadata({ - body: commentBody, - fetchRatios: true, - postType - }) - const jsonMetadata = makeJsonMetadata(meta, parentTags || ['ecency']) + userActivityMutation.mutate({ + pointsTy: PointActivityIds.COMMENT, + transactionId: response.id, + }); + setIsSending(false); - console.log( - currentAccount, - pinCode, - parentAuthor, - parentPermlink, - permlink, - commentBody, - jsonMetadata - ); + dispatch( + toastNotification( + intl.formatMessage({ + id: 'alert.success', + }), + ), + ); + // add comment cache entry + const _cacheCommentData = { + author, + permlink, + url, + parent_author: parentAuthor, + parent_permlink: parentPermlink, + markdownBody: commentBody, + json_metadata: jsonMetadata, + }; - try { - const response = await postComment( - currentAccount, - pinCode, - parentAuthor, - parentPermlink, - permlink, - commentBody, - jsonMetadata - ) + dispatch( + updateCommentCache(`${author}/${permlink}`, _cacheCommentData, { + parentTags: parentTags || ['ecency'], + }), + ); - userActivityMutation.mutate({ - pointsTy: PointActivityIds.COMMENT, - transactionId: response.id, - }); - setIsSending(false); - - dispatch( - toastNotification( - intl.formatMessage({ - id: 'alert.success', - }), - ), - ); - - // add comment cache entry - const _cacheCommentData = { - author, - permlink, - url, - parent_author: parentAuthor, - parent_permlink: parentPermlink, - markdownBody: commentBody, - json_metadata: jsonMetadata - } - - dispatch( - updateCommentCache( - `${author}/${permlink}`, - _cacheCommentData, - { - parentTags: parentTags || ['ecency'], - }, - ), - ); - - return _cacheCommentData; - - - } catch (error) { - console.log(error); - Alert.alert( - intl.formatMessage({ - id: 'alert.something_wrong', - }), - error.message || JSON.stringify(error), - ); - - setIsSending(false); - return false; - - } - - - } + return _cacheCommentData; + } catch (error) { + console.log(error); + Alert.alert( + intl.formatMessage({ + id: 'alert.something_wrong', + }), + error.message || JSON.stringify(error), + ); + setIsSending(false); return false; - }; - - - - //feteced lates wafves container and post wave to that container - const _submitWave = async (body: string) => { - - try { - const _wavesHost = 'ecency.waves' //TODO: make waves host selection dynamic - const latestWavesPost = await wavesQueries.fetchLatestWavesContainer(_wavesHost); - - const _cacheCommentData = await _submitReply(body, latestWavesPost, PostTypes.WAVE) - - if (_cacheCommentData) { - pusblishWaveMutation.mutate(_cacheCommentData) - } - - return _cacheCommentData - } catch (err) { - Alert.alert("Fail", err.message) - return false; - } + } } + return false; + }; + // feteced lates wafves container and post wave to that container + const _submitWave = async (body: string) => { + try { + const _wavesHost = 'ecency.waves'; // TODO: make waves host selection dynamic + const latestWavesPost = await wavesQueries.fetchLatestWavesContainer(_wavesHost); - return { - submitReply: _submitReply, - submitWave: _submitWave, - isSending + const _cacheCommentData = await _submitReply(body, latestWavesPost, PostTypes.WAVE); + + if (_cacheCommentData) { + pusblishWaveMutation.mutate(_cacheCommentData); + } + + return _cacheCommentData; + } catch (err) { + Alert.alert('Fail', err.message); + return false; } + }; -} \ No newline at end of file + return { + submitReply: _submitReply, + submitWave: _submitWave, + isSending, + }; +}; diff --git a/src/components/sideMenu/container/sideMenuContainer.tsx b/src/components/sideMenu/container/sideMenuContainer.tsx index 4edb1cc82..98453118c 100644 --- a/src/components/sideMenu/container/sideMenuContainer.tsx +++ b/src/components/sideMenu/container/sideMenuContainer.tsx @@ -2,12 +2,12 @@ import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; // Actions +import { useDrawerStatus } from '@react-navigation/drawer'; import { logout, toggleAccountsBottomSheet } from '../../../redux/actions/uiAction'; import { setInitPosts, setFeedPosts } from '../../../redux/actions/postsAction'; // Component import SideMenuView from '../view/sideMenuView'; -import { useDrawerStatus } from '@react-navigation/drawer'; import { updateCurrentAccount } from '../../../redux/actions/accountAction'; import { getUser } from '../../../providers/hive/dhive'; import bugsnapInstance from '../../../config/bugsnag'; @@ -16,40 +16,33 @@ const SideMenuContainer = ({ navigation }) => { const dispatch = useDispatch(); const drawerStatus = useDrawerStatus(); - const isLoggedIn = useSelector((state) => state.application.isLoggedIn); const currentAccount = useSelector((state) => state.account.currentAccount); const isVisibleAccountsBottomSheet = useSelector( (state) => state.ui.isVisibleAccountsBottomSheet, ); - - useEffect(()=>{ - if(drawerStatus === 'open'){ - //update profile on drawer open + useEffect(() => { + if (drawerStatus === 'open') { + // update profile on drawer open _updateUserData(); } - - }, [drawerStatus]) + }, [drawerStatus]); - - //fetches and update user data + // fetches and update user data const _updateUserData = async () => { - try{ - if(currentAccount?.username){ - let accountData = await getUser(currentAccount.username); - if(accountData){ - dispatch(updateCurrentAccount({...currentAccount, ...accountData})) - } + try { + if (currentAccount?.username) { + const accountData = await getUser(currentAccount.username); + if (accountData) { + dispatch(updateCurrentAccount({ ...currentAccount, ...accountData })); + } } - - } catch(err){ - console.warn("failed to update user data") + } catch (err) { + console.warn('failed to update user data'); bugsnapInstance.notify(err); } - - } - + }; const _navigateToRoute = (route = null) => { if (route) { diff --git a/src/components/snippetEditorModal/snippetEditorModalStyles.ts b/src/components/snippetEditorModal/snippetEditorModalStyles.ts index 3d0425b4c..da53564df 100644 --- a/src/components/snippetEditorModal/snippetEditorModalStyles.ts +++ b/src/components/snippetEditorModal/snippetEditorModalStyles.ts @@ -2,63 +2,61 @@ import { TextStyle, StyleSheet, ViewStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ - modalStyle: { - flex: 1, - backgroundColor: '$primaryBackgroundColor', - margin:0, - paddingTop:32, - paddingBottom:8 - }, - container:{ - flexGrow:1, - marginTop:24, - paddingHorizontal:24, - }, - inputContainer:{ - flex:1 - } as ViewStyle, - titleInput:{ - color: '$primaryBlack', - fontWeight: 'bold', - fontSize: 18, - textAlignVertical: 'top', - paddingVertical: 0, - backgroundColor:'$primaryBackgroundColor', - borderBottomWidth:StyleSheet.hairlineWidth, - borderBottomColor:'$primaryDarkGray' - } as TextStyle, - bodyWrapper: { - fontSize: 16, - paddingTop: 16, - paddingBottom: 0, // On android side, textinput has default padding - color: '$primaryBlack', - textAlignVertical: 'top', - backgroundColor: '$primaryBackgroundColor', - }, - btnText:{ - color:'$pureWhite' - } as TextStyle, - saveButton:{ - - backgroundColor:'$primaryBlue', - width:150, - paddingVertical:16, - borderRadius:32, - justifyContent:'center', - alignItems:'center' - } as ViewStyle, - closeButton:{ - marginRight:16, - paddingVertical:8, - borderRadius:16, - justifyContent:'center', - alignItems:'center' - } as ViewStyle, - actionPanel:{ - flexDirection:'row', - justifyContent:'flex-end', - alignItems:'center', - marginBottom:16 - } as ViewStyle, - -}) \ No newline at end of file + modalStyle: { + flex: 1, + backgroundColor: '$primaryBackgroundColor', + margin: 0, + paddingTop: 32, + paddingBottom: 8, + }, + container: { + flexGrow: 1, + marginTop: 24, + paddingHorizontal: 24, + }, + inputContainer: { + flex: 1, + } as ViewStyle, + titleInput: { + color: '$primaryBlack', + fontWeight: 'bold', + fontSize: 18, + textAlignVertical: 'top', + paddingVertical: 0, + backgroundColor: '$primaryBackgroundColor', + borderBottomWidth: StyleSheet.hairlineWidth, + borderBottomColor: '$primaryDarkGray', + } as TextStyle, + bodyWrapper: { + fontSize: 16, + paddingTop: 16, + paddingBottom: 0, // On android side, textinput has default padding + color: '$primaryBlack', + textAlignVertical: 'top', + backgroundColor: '$primaryBackgroundColor', + }, + btnText: { + color: '$pureWhite', + } as TextStyle, + saveButton: { + backgroundColor: '$primaryBlue', + width: 150, + paddingVertical: 16, + borderRadius: 32, + justifyContent: 'center', + alignItems: 'center', + } as ViewStyle, + closeButton: { + marginRight: 16, + paddingVertical: 8, + borderRadius: 16, + justifyContent: 'center', + alignItems: 'center', + } as ViewStyle, + actionPanel: { + flexDirection: 'row', + justifyContent: 'flex-end', + alignItems: 'center', + marginBottom: 16, + } as ViewStyle, +}); diff --git a/src/components/snippetsModal/snippetsModalStyles.ts b/src/components/snippetsModal/snippetsModalStyles.ts index 947bfc5bd..b511d6c2c 100644 --- a/src/components/snippetsModal/snippetsModalStyles.ts +++ b/src/components/snippetsModal/snippetsModalStyles.ts @@ -9,44 +9,43 @@ export default EStyleSheet.create({ }, bodyWrapper: { flex: 3, - paddingHorizontal:16 + paddingHorizontal: 16, }, - floatingContainer:{ - position:'absolute', - bottom:0, - right:20, - justifyContent:'flex-end', - zIndex:10 + floatingContainer: { + position: 'absolute', + bottom: 0, + right: 20, + justifyContent: 'flex-end', + zIndex: 10, } as ViewStyle, itemWrapper: { paddingHorizontal: 16, - paddingVertical:8, + paddingVertical: 8, borderRadius: 8, backgroundColor: '$primaryBackgroundColor', }, - itemHeader:{ - flexDirection:'row', - alignItems:'center', - height:35 + itemHeader: { + flexDirection: 'row', + alignItems: 'center', + height: 35, }, itemWrapperGray: { backgroundColor: '$primaryLightBackground', }, - itemIcon:{ - color:'$primaryDarkGray', + itemIcon: { + color: '$primaryDarkGray', }, - itemIconWrapper:{ - marginLeft:8, + itemIconWrapper: { + marginLeft: 8, }, title: { fontWeight: '700', - flex:1, - fontSize:16, - color:'$primaryBlack' + flex: 1, + fontSize: 16, + color: '$primaryBlack', }, body: { - paddingBottom:8, - color:'$primaryBlack' + paddingBottom: 8, + color: '$primaryBlack', }, - }); diff --git a/src/components/tabbedPosts/container/tabbedPosts.tsx b/src/components/tabbedPosts/container/tabbedPosts.tsx index c9a933adf..edff07ec3 100644 --- a/src/components/tabbedPosts/container/tabbedPosts.tsx +++ b/src/components/tabbedPosts/container/tabbedPosts.tsx @@ -4,7 +4,6 @@ import { TabbedPostsProps } from '../services/tabbedPostsModels'; import { StackedTabBar, TabItem } from '../view/stackedTabBar'; import TabContent from '../view/tabContent'; - export const TabbedPosts = ({ filterOptions, filterOptionsValue, @@ -20,45 +19,48 @@ export const TabbedPosts = ({ onTabChange, ...props }: TabbedPostsProps) => { + // initialize state + const [initialTabIndex] = useState( + selectedOptionIndex == 0 && stackedTabs ? filterOptions.length : selectedOptionIndex, + ); - //initialize state - const [initialTabIndex] = useState(selectedOptionIndex == 0 && stackedTabs ? filterOptions.length : selectedOptionIndex) - - const mainFilters = filterOptions.map((label, index) => ({ - filterKey: filterOptionsValue[index], - label - } as TabItem)); + const mainFilters = filterOptions.map( + (label, index) => + ({ + filterKey: filterOptionsValue[index], + label, + } as TabItem), + ); const subFilters = feedSubfilterOptions - ? feedSubfilterOptions.map((label, index) => ({ - filterKey: feedSubfilterOptionsValue[index], - label - } as TabItem)) + ? feedSubfilterOptions.map( + (label, index) => + ({ + filterKey: feedSubfilterOptionsValue[index], + label, + } as TabItem), + ) : []; - const combinedFilters = [...mainFilters, ...subFilters] + const combinedFilters = [...mainFilters, ...subFilters]; - const [selectedFilter, setSelectedFilter] = useState(combinedFilters[initialTabIndex].filterKey) - const [filterScrollRequest, createFilterScrollRequest] = useState(null) + const [selectedFilter, setSelectedFilter] = useState(combinedFilters[initialTabIndex].filterKey); + const [filterScrollRequest, createFilterScrollRequest] = useState(null); - - - //components actions + // components actions const _onFilterSelect = (filter: string) => { if (filter === selectedFilter) { - createFilterScrollRequest(selectedFilter) + createFilterScrollRequest(selectedFilter); } else { - setSelectedFilter(filter) + setSelectedFilter(filter); } - } + }; const _onScrollRequestProcessed = () => { createFilterScrollRequest(null); - } + }; - - - //initialize first set of pages + // initialize first set of pages const pages = combinedFilters.map((filter, index) => { if (tabContentOverrides && tabContentOverrides.has(index)) { return tabContentOverrides.get(index); @@ -76,11 +78,10 @@ export const TabbedPosts = ({ onScrollRequestProcessed={_onScrollRequestProcessed} {...props} /> - ) + ); }); - - //render tab bar + // render tab bar const _renderTabBar = (props) => { return ( - ) - } - + ); + }; return ( ); - -} +}; diff --git a/src/components/tabbedPosts/services/tabbedPostsFetch.ts b/src/components/tabbedPosts/services/tabbedPostsFetch.ts index 6fd397b16..d929715f1 100644 --- a/src/components/tabbedPosts/services/tabbedPostsFetch.ts +++ b/src/components/tabbedPosts/services/tabbedPostsFetch.ts @@ -184,12 +184,11 @@ export const loadPosts = async ({ } }; -export const fetchPromotedEntries = async (username: string, nsfwFilter:string) => { +export const fetchPromotedEntries = async (username: string, nsfwFilter: string) => { try { const posts = await getPromotedEntries(username); - return Array.isArray(posts) ? filterNsfwPost(posts, nsfwFilter) : []; - + return Array.isArray(posts) ? filterNsfwPost(posts, nsfwFilter) : []; } catch (err) { console.warn('Failed to get promoted posts, ', err); } diff --git a/src/components/tabbedPosts/view/tabContent.tsx b/src/components/tabbedPosts/view/tabContent.tsx index 33273eff3..a912b8026 100644 --- a/src/components/tabbedPosts/view/tabContent.tsx +++ b/src/components/tabbedPosts/view/tabContent.tsx @@ -1,6 +1,11 @@ import React, { useState, useEffect, useRef } from 'react'; import { useSelector, useDispatch } from 'react-redux'; -import { AppState, NativeEventSubscription, NativeScrollEvent, NativeSyntheticEvent } from 'react-native'; +import { + AppState, + NativeEventSubscription, + NativeScrollEvent, + NativeSyntheticEvent, +} from 'react-native'; import { debounce } from 'lodash'; import BackgroundTimer from 'react-native-background-timer'; import PostsList from '../../postsList'; @@ -41,7 +46,7 @@ const TabContent = ({ }: TabContentProps) => { let _isMounted = true; - //redux properties + // redux properties const dispatch = useDispatch(); const isLoggedIn = useSelector((state) => state.application.isLoggedIn); const nsfw = useSelector((state) => state.application.nsfw); @@ -49,11 +54,10 @@ const TabContent = ({ const currentAccount = useSelector((state) => state.account.currentAccount); const initPosts = useSelector((state) => state.posts.initPosts); - - const username = currentAccount.username; + const { username } = currentAccount; const userPinned = currentAccount.about?.profile?.pinned; - //state + // state const [posts, setPosts] = useState([]); const [promotedPosts, setPromotedPosts] = useState([]); const [sessionUser, setSessionUser] = useState(username); @@ -62,21 +66,20 @@ const TabContent = ({ const [enableScrollTop, setEnableScrollTop] = useState(false); const [curPinned, setCurPinned] = useState(pinnedPermlink); - //refs - let postsListRef = useRef(); + // refs + const postsListRef = useRef(); const appState = useRef(AppState.currentState); - const appStateSubRef = useRef() + const appStateSubRef = useRef(); const postsRef = useRef(posts); const sessionUserRef = useRef(sessionUser); const postFetchTimerRef = useRef(null); - //init state refs; + // init state refs; postsRef.current = posts; sessionUserRef.current = sessionUser; - //side effects + // side effects useEffect(() => { - if (isFeedScreen) { appStateSubRef.current = AppState.addEventListener('change', _handleAppStateChange); } @@ -88,7 +91,7 @@ const TabContent = ({ useEffect(() => { if (isConnected && (username !== sessionUser || forceLoadPosts)) { - _initContent(false, username); + _initContent(false, username); } }, [username, forceLoadPosts]); @@ -113,7 +116,7 @@ const TabContent = ({ const _cleanup = () => { _isMounted = false; if (postFetchTimerRef.current) { - BackgroundTimer.clearTimeout(postFetchTimerRef.current) + BackgroundTimer.clearTimeout(postFetchTimerRef.current); postFetchTimerRef.current = null; } if (isFeedScreen && appStateSubRef.current) { @@ -121,7 +124,7 @@ const TabContent = ({ } }; - //actions + // actions const _handleAppStateChange = (nextAppState) => { if ( appState.current.match(/inactive|background/) && @@ -166,7 +169,7 @@ const TabContent = ({ } }; - //fetch posts from server + // fetch posts from server const _loadPosts = async ({ shouldReset = false, isLatestPostsCheck = false, @@ -225,7 +228,7 @@ const TabContent = ({ } }; - //schedules post fetch + // schedules post fetch const _scheduleLatestPostsCheck = (firstPost: any) => { if (firstPost) { if (postFetchTimerRef.current) { @@ -241,13 +244,12 @@ const TabContent = ({ isLatestPostsCheck, }); }, timeLeft); - } }; - //processes response from loadPost + // processes response from loadPost const _postProcessLoadResult = ({ updatedPosts, latestPosts }: any) => { - //process new posts avatart + // process new posts avatart if (latestPosts && Array.isArray(latestPosts)) { if (latestPosts.length > 0) { setLatestPosts(latestPosts); @@ -256,14 +258,14 @@ const TabContent = ({ } } - //process returned data + // process returned data if (Array.isArray(updatedPosts)) { if (updatedPosts.length) { - //match new and old first post + // match new and old first post const firstPostChanged = posts.length == 0 || posts[0].permlink !== updatedPosts[0].permlink; if (isFeedScreen && firstPostChanged) { - //schedule refetch of new posts by checking time of current post + // schedule refetch of new posts by checking time of current post _scheduleLatestPostsCheck(updatedPosts[0]); if (isInitialTab) { @@ -271,14 +273,14 @@ const TabContent = ({ } } } else if (isFeedScreen && isInitialTab) { - //clear posts cache if no first tab posts available, precautionary measure for accoutn change + // clear posts cache if no first tab posts available, precautionary measure for accoutn change dispatch(setInitPosts([])); } setPosts(updatedPosts); } }; - //view related routines + // view related routines const _onPostsPopupPress = () => { _scrollToTop(); _getPromotedPosts(); @@ -303,7 +305,7 @@ const TabContent = ({ } }; - //view rendereres + // view rendereres const _renderEmptyContent = () => { return ; }; @@ -317,8 +319,8 @@ const TabContent = ({ ); const _onScroll = (event: NativeSyntheticEvent) => { - let currentOffset = event.nativeEvent.contentOffset.y; - let scrollUp = currentOffset < scrollOffset; + const currentOffset = event.nativeEvent.contentOffset.y; + const scrollUp = currentOffset < scrollOffset; scrollOffset = currentOffset; if (scrollUp && !blockPopup && currentOffset > SCROLL_POPUP_THRESHOLD) { @@ -329,9 +331,9 @@ const TabContent = ({ // show quick reply modal const _showQuickReplyModal = (post: any) => { if (isLoggedIn) { - dispatch(showReplyModal({mode:'comment', parentPost:post})); + dispatch(showReplyModal({ mode: 'comment', parentPost: post })); } else { - //TODO: show proper alert message + // TODO: show proper alert message console.log('Not LoggedIn'); } }; diff --git a/src/components/textBoxWithCopy/textBoxWithCopy.tsx b/src/components/textBoxWithCopy/textBoxWithCopy.tsx index 738ebfc2b..c5980d46e 100644 --- a/src/components/textBoxWithCopy/textBoxWithCopy.tsx +++ b/src/components/textBoxWithCopy/textBoxWithCopy.tsx @@ -1,12 +1,12 @@ import React from 'react'; import { useIntl } from 'react-intl'; import { View, Text } from 'react-native'; -import IconButton from '../iconButton'; import Clipboard from '@react-native-clipboard/clipboard'; +import { useDispatch } from 'react-redux'; +import IconButton from '../iconButton'; // Styles import styles from './textBoxWithCopyStyles'; -import { useDispatch } from 'react-redux'; import { toastNotification } from '../../redux/actions/uiAction'; interface TextBoxWithCopyProps { @@ -23,7 +23,7 @@ const TextBoxWithCopy = ({ label, value, renderSecondButton }: TextBoxWithCopyPr {label} - {renderSecondButton ? renderSecondButton : null} + {renderSecondButton || null} @@ -33,7 +33,7 @@ const TextBoxWithCopy = ({ label, value, renderSecondButton }: TextBoxWithCopyPr { onNext(true); - } + }; const _renderDescription = (text) => {text}; const _renderCenterDescription = (text, extraStyles = {}) => ( diff --git a/src/components/upvotePopover/container/upvotePopover.tsx b/src/components/upvotePopover/container/upvotePopover.tsx index dc418af8b..ddad5d37a 100644 --- a/src/components/upvotePopover/container/upvotePopover.tsx +++ b/src/components/upvotePopover/container/upvotePopover.tsx @@ -51,7 +51,7 @@ import { CacheStatus } from '../../../redux/reducers/cacheReducer'; import showLoginAlert from '../../../utils/showLoginAlert'; import { delay } from '../../../utils/editor'; -interface Props { } +interface Props {} interface PopoverOptions { anchorRect: Rect; content: any; @@ -66,7 +66,7 @@ interface PopoverOptions { * */ -const UpvotePopover = forwardRef(({ }: Props, ref) => { +const UpvotePopover = forwardRef(({}: Props, ref) => { const intl = useIntl(); const dispatch = useAppDispatch(); @@ -94,7 +94,6 @@ const UpvotePopover = forwardRef(({ }: Props, ref) => { const [sliderValue, setSliderValue] = useState(1); const [amount, setAmount] = useState('0.00000'); - useImperativeHandle(ref, () => ({ showPopover: ({ anchorRect: _anchorRect, @@ -141,19 +140,22 @@ const UpvotePopover = forwardRef(({ }: Props, ref) => { }, []); useEffect(() => { - let _upvotePercent = 1; - switch(postType){ - case PostTypes.POST: _upvotePercent = postUpvotePercent; break; - case PostTypes.COMMENT: _upvotePercent = commentUpvotePercent; break; - case PostTypes.WAVE: _upvotePercent = waveUpvotePercent; break; + switch (postType) { + case PostTypes.POST: + _upvotePercent = postUpvotePercent; + break; + case PostTypes.COMMENT: + _upvotePercent = commentUpvotePercent; + break; + case PostTypes.WAVE: + _upvotePercent = waveUpvotePercent; + break; } - setSliderValue(_upvotePercent) - _calculateEstimatedAmount(_upvotePercent) - + setSliderValue(_upvotePercent); + _calculateEstimatedAmount(_upvotePercent); }, [content, postType]); - // Component Functions const _calculateEstimatedAmount = async (value: number = sliderValue) => { if (currentAccount && Object.entries(currentAccount).length !== 0) { @@ -204,7 +206,13 @@ const UpvotePopover = forwardRef(({ }: Props, ref) => { return; } setIsVoted(!!sliderValue); - _updateVoteCache(_author, _permlink, amount, false, !!sliderValue ? CacheStatus.PUBLISHED : CacheStatus.DELETED); + _updateVoteCache( + _author, + _permlink, + amount, + false, + sliderValue ? CacheStatus.PUBLISHED : CacheStatus.DELETED, + ); }) .catch((err) => { _updateVoteCache(_author, _permlink, amount, false, CacheStatus.FAILED); @@ -267,7 +275,13 @@ const UpvotePopover = forwardRef(({ }: Props, ref) => { transactionId: response.id, }); setIsVoted(!!sliderValue); - _updateVoteCache(_author, _permlink, amount, true, !!sliderValue ? CacheStatus.PUBLISHED : CacheStatus.DELETED); + _updateVoteCache( + _author, + _permlink, + amount, + true, + sliderValue ? CacheStatus.PUBLISHED : CacheStatus.DELETED, + ); }) .catch((err) => { dispatch( @@ -286,17 +300,21 @@ const UpvotePopover = forwardRef(({ }: Props, ref) => { const _setUpvotePercent = (value) => { if (value) { - - let _dispatchAction:any = null - switch(postType){ - case PostTypes.POST: _dispatchAction = setPostUpvotePercent; break; - case PostTypes.COMMENT: _dispatchAction = setCommentUpvotePercent; break; - case PostTypes.WAVE: _dispatchAction = setWaveUpvotePercent; break; + let _dispatchAction: any = null; + switch (postType) { + case PostTypes.POST: + _dispatchAction = setPostUpvotePercent; + break; + case PostTypes.COMMENT: + _dispatchAction = setCommentUpvotePercent; + break; + case PostTypes.WAVE: + _dispatchAction = setWaveUpvotePercent; + break; } - if(_dispatchAction){ - dispatch(_dispatchAction(value)) + if (_dispatchAction) { + dispatch(_dispatchAction(value)); } - } }; @@ -311,7 +329,7 @@ const UpvotePopover = forwardRef(({ }: Props, ref) => { const percent = Math.floor(sliderValue * 10000 * (isDownvote ? -1 : 1)); const rshares = calculateEstimatedRShares(currentAccount, percent) * (isDownvote ? -1 : 1); - + // update redux const postPath = `${author || ''}/${permlink || ''}`; const curTime = new Date().getTime(); @@ -348,7 +366,7 @@ const UpvotePopover = forwardRef(({ }: Props, ref) => { const sliderColor = isDownVoted ? '#ec8b88' : '#357ce6'; - const _minSliderVal = isVoted || isDownVoted ? 0 : 0.01 + const _minSliderVal = isVoted || isDownVoted ? 0 : 0.01; return ( diff --git a/src/components/votersDisplay/view/votersDisplayView.js b/src/components/votersDisplay/view/votersDisplayView.js index 9c3086497..d4f61ce3f 100644 --- a/src/components/votersDisplay/view/votersDisplayView.js +++ b/src/components/votersDisplay/view/votersDisplayView.js @@ -1,7 +1,6 @@ import React from 'react'; import { SafeAreaView, FlatList } from 'react-native'; - // Utils import { useNavigation } from '@react-navigation/native'; import { getTimeFromNow } from '../../../utils/time'; diff --git a/src/components/wallet/view/walletView.js b/src/components/wallet/view/walletView.js index 79cb87f05..74505fc47 100644 --- a/src/components/wallet/view/walletView.js +++ b/src/components/wallet/view/walletView.js @@ -112,7 +112,6 @@ const WalletView = ({ setEstimatedWalletValue, selectedUser, handleOnScroll }) = )} - )} ); diff --git a/src/components/webViewModal/webViewModal.tsx b/src/components/webViewModal/webViewModal.tsx index aca0ecd2a..2b6dd7fa5 100644 --- a/src/components/webViewModal/webViewModal.tsx +++ b/src/components/webViewModal/webViewModal.tsx @@ -1,8 +1,8 @@ import React, { useEffect, useState } from 'react'; import { useIntl } from 'react-intl'; +import WebView from 'react-native-webview'; import { useAppDispatch, useAppSelector } from '../../hooks'; import { hideWebViewModal } from '../../redux/actions/uiAction'; -import WebView from 'react-native-webview'; import { hsOptions } from '../../constants/hsOptions'; import { Modal } from '..'; import styles from './webViewModalStyles'; diff --git a/src/constants/defaultAssets.ts b/src/constants/defaultAssets.ts index 302e263a1..8308113fd 100644 --- a/src/constants/defaultAssets.ts +++ b/src/constants/defaultAssets.ts @@ -24,18 +24,17 @@ const DEFAULT_ASSETS = [ symbol: 'HBD', notCrypto: false, isEngine: false, - } + }, ] as CoinBase[]; - export enum ASSET_IDS { - ECENCY= 'ecency', + ECENCY = 'ecency', HIVE = 'hive', HBD = 'hive_dollar', HP = 'hive_power', SPK = 'SPK', LARYNX = 'LARYNX', - LARYNX_POWER = 'LP' -}; + LARYNX_POWER = 'LP', +} export default DEFAULT_ASSETS; diff --git a/src/constants/options/api.js b/src/constants/options/api.js index 53962d1a3..13ba1de0f 100644 --- a/src/constants/options/api.js +++ b/src/constants/options/api.js @@ -15,12 +15,12 @@ export const VALUE = [ ]; export const SERVER_LIST = [ - "https://rpc.ecency.com", - "https://api.hive.blog", - "https://api.deathwing.me", - "https://api.pharesim.me", - "https://anyx.io", - "https://rpc.ausbit.dev", - "https://api.openhive.network", - "https://api.hivekings.com" + 'https://rpc.ecency.com', + 'https://api.hive.blog', + 'https://api.deathwing.me', + 'https://api.pharesim.me', + 'https://anyx.io', + 'https://rpc.ausbit.dev', + 'https://api.openhive.network', + 'https://api.hivekings.com', ]; diff --git a/src/constants/options/points.js b/src/constants/options/points.js index af98f96dc..ec6ca303a 100644 --- a/src/constants/options/points.js +++ b/src/constants/options/points.js @@ -19,7 +19,7 @@ export default { icon: 'trophy-outline', textKey: 'community_reward', iconType: 'MaterialCommunityIcons', - point: 0.1 + point: 0.1, }, 160: { icon: 'target', @@ -93,7 +93,7 @@ export default { iconType: 'MaterialCommunityIcons', point: 10, }, - 'default': { + default: { icon: 'local-activity', textKey: 'points_activity', iconType: 'MaterialIcons', diff --git a/src/constants/postTypes.ts b/src/constants/postTypes.ts index 81d06da2c..90ac1694c 100644 --- a/src/constants/postTypes.ts +++ b/src/constants/postTypes.ts @@ -1,5 +1,5 @@ export enum PostTypes { POST = 'post', COMMENT = 'comment', - WAVE = 'wave' + WAVE = 'wave', } diff --git a/src/constants/routeNames.js b/src/constants/routeNames.js index 062e9273b..20fcdfca5 100644 --- a/src/constants/routeNames.js +++ b/src/constants/routeNames.js @@ -39,7 +39,6 @@ const ROUTES = { WELCOME: `Welcome${SCREEN_SUFFIX}`, BACKUP_KEYS: `BackupKeys${SCREEN_SUFFIX}`, TRADE: `Trade${SCREEN_SUFFIX}`, - }, MODALS: { ASSETS_SELECT: `AssetsSelect${MODAL_SUFFIX}`, diff --git a/src/containers/profileContainer.js b/src/containers/profileContainer.js index 1c1d1e582..4589cd54f 100644 --- a/src/containers/profileContainer.js +++ b/src/containers/profileContainer.js @@ -484,7 +484,6 @@ class ProfileContainer extends Component { if (isLoggedIn && !nextProps.isLoggedIn) { navigation.navigate(ROUTES.SCREENS.LOGIN); - return; } } diff --git a/src/navigation/botomTabNavigator.tsx b/src/navigation/botomTabNavigator.tsx index 82ea69055..bf49dfefa 100644 --- a/src/navigation/botomTabNavigator.tsx +++ b/src/navigation/botomTabNavigator.tsx @@ -60,7 +60,6 @@ export const BottomTabNavigator = () => { iconName: 'notifications', // read in bottomTabBarView }} /> - ); }; diff --git a/src/providers/coingecko/coingecko.ts b/src/providers/coingecko/coingecko.ts index 0afb4794c..3c46898ea 100644 --- a/src/providers/coingecko/coingecko.ts +++ b/src/providers/coingecko/coingecko.ts @@ -24,7 +24,7 @@ export const fetchMarketChart = async ( interval, }; - /** + /** * NOTE: skipping this failsafe since for now we can only use 'daily' interval // failsafe for accidental invalid parameters // ref: https://www.coingecko.com/en/api/documentation diff --git a/src/providers/coingecko/converters.ts b/src/providers/coingecko/converters.ts index 5210d273e..4a3260eb6 100644 --- a/src/providers/coingecko/converters.ts +++ b/src/providers/coingecko/converters.ts @@ -11,7 +11,6 @@ export const convertChartItem = (rawData: any) => { }; export const convertMarketData = (rawData: any) => { - return { prices: rawData.prices ? rawData.prices.map(convertChartItem) : [], marketCaps: rawData.market_caps ? rawData.market_caps.map(convertChartItem) : [], diff --git a/src/providers/ecency/converters.ts b/src/providers/ecency/converters.ts index 56006b77a..d21f66a05 100644 --- a/src/providers/ecency/converters.ts +++ b/src/providers/ecency/converters.ts @@ -6,7 +6,7 @@ import { LatestQuotes, QuoteItem, ReferralStat, - Draft + Draft, } from './ecency.types'; export const convertReferral = (rawData: any) => { @@ -14,7 +14,7 @@ export const convertReferral = (rawData: any) => { _id: rawData.id || 0, referral: rawData.referral || '', referredUsername: rawData.username || '', - isRewarded: rawData.rewarded ? true : false, + isRewarded: !!rawData.rewarded, timestamp: new Date(rawData.created) || new Date(), } as Referral; }; @@ -37,23 +37,23 @@ export const convertQuoteItem = (rawData: any, currencyRate: number) => { } as QuoteItem; }; -export const convertDraft = (rawData:any) => { - if(!rawData){ - return null +export const convertDraft = (rawData: any) => { + if (!rawData) { + return null; } return { - _id:rawData._id, - title:rawData.title, - body:rawData.body, - tags_arr:rawData.tags_arr, - tags:rawData.tags, - meta:rawData.meta, - modified:rawData.modified, - created:rawData.created, - timestamp:rawData.timestamp - } as Draft -} + _id: rawData._id, + title: rawData.title, + body: rawData.body, + tags_arr: rawData.tags_arr, + tags: rawData.tags, + meta: rawData.meta, + modified: rawData.modified, + created: rawData.created, + timestamp: rawData.timestamp, + } as Draft; +}; export const convertLatestQuotes = (rawData: any, currencyRate: number) => { return { diff --git a/src/providers/ecency/ePoint.ts b/src/providers/ecency/ePoint.ts index 4af889cbd..49afe5ff9 100644 --- a/src/providers/ecency/ePoint.ts +++ b/src/providers/ecency/ePoint.ts @@ -10,7 +10,7 @@ import { EcencyUser, UserPoint } from './ecency.types'; * @param tx transaction id * @returns */ -export const userActivity = async (ty: number, tx: string = '', bl: string | number = '') => { +export const userActivity = async (ty: number, tx = '', bl: string | number = '') => { try { const data: { ty: number; diff --git a/src/providers/ecency/ecency.ts b/src/providers/ecency/ecency.ts index 26a0ddc0b..7a53568ee 100644 --- a/src/providers/ecency/ecency.ts +++ b/src/providers/ecency/ecency.ts @@ -31,13 +31,13 @@ import { * ************************************ */ -export const getFiatHbdRate = (fiatCode:string) => +export const getFiatHbdRate = (fiatCode: string) => ecencyApi .get(`/private-api/market-data/${fiatCode}/hbd`) .then((resp) => resp.data) .catch((err) => { bugsnagInstance.notify(err); - //TODO: save currency rate of offline values + // TODO: save currency rate of offline values return 1; }); @@ -53,7 +53,7 @@ export const getLatestQuotes = async (currencyRate: number): Promise { const res = await ecencyApi.post('/private-api/drafts-add', newDraft); const rawData = res.data?.drafts; - if(!rawData){ - throw new Error("Invalid response, drafts data not returned") + if (!rawData) { + throw new Error('Invalid response, drafts data not returned'); } const data = rawData.length > 0 ? rawData.map(convertDraft) : []; @@ -526,7 +526,7 @@ export const searchPath = async (q: string) => { * @param random random * @returns array of accounts */ -export const searchAccount = async (q: string = '', limit: number = 20, random: number = 0) => { +export const searchAccount = async (q = '', limit = 20, random = 0) => { try { const data = { q, @@ -549,7 +549,7 @@ export const searchAccount = async (q: string = '', limit: number = 20, random: * @param random random * @returns array of accounts */ -export const searchTag = async (q: string = '', limit: number = 20, random: number = 0) => { +export const searchTag = async (q = '', limit = 20, random = 0) => { try { const data = { q, @@ -782,7 +782,7 @@ export const getPromotedEntries = async (username: string) => { * post inapp purchase method to call * @param data PurchaseRequestData * @returns - **/ + * */ export const purchaseOrder = (data: PurchaseRequestData) => api .post('/purchase-order', data) diff --git a/src/providers/hive-engine/converters.ts b/src/providers/hive-engine/converters.ts index 0f61c326f..f043f583f 100644 --- a/src/providers/hive-engine/converters.ts +++ b/src/providers/hive-engine/converters.ts @@ -1,7 +1,20 @@ +import { + EngineMetric, + HistoryItem, + HiveEngineToken, + MarketData, + Token, + TokenBalance, + TokenMetadata, + TokenStatus, +} from './hiveEngine.types'; -import { EngineMetric, HistoryItem, HiveEngineToken, MarketData, Token, TokenBalance, TokenMetadata, TokenStatus } from './hiveEngine.types'; - -export const convertEngineToken = (balanceObj: TokenBalance, token?: Token, metrics?: EngineMetric, tokenStatus?:TokenStatus) => { +export const convertEngineToken = ( + balanceObj: TokenBalance, + token?: Token, + metrics?: EngineMetric, + tokenStatus?: TokenStatus, +) => { if (!balanceObj) { return null; } @@ -37,50 +50,44 @@ export const convertEngineToken = (balanceObj: TokenBalance, token?: Token, metr } as HiveEngineToken; }; - export const convertRewardsStatus = (rawData: any) => { - return { - symbol:rawData.symbol, - pendingToken:rawData.pending_token, - precision:rawData.precision, - pendingRewards: rawData.pending_token / Math.pow(10, rawData.precision) - } as TokenStatus -} - + symbol: rawData.symbol, + pendingToken: rawData.pending_token, + precision: rawData.precision, + pendingRewards: rawData.pending_token / Math.pow(10, rawData.precision), + } as TokenStatus; +}; export const convertMarketData = (rawData: any) => { - - if(!rawData){ + if (!rawData) { return null; } return { - quoteVolume:parseFloat(rawData.quoteVolume), - baseVolume:parseFloat(rawData.baseVolume), - low:parseFloat(rawData.low), - close:parseFloat(rawData.close), - high:parseFloat(rawData.high), - open:parseFloat(rawData.open), - timestamp:rawData.timestamp, - } as MarketData -} - + quoteVolume: parseFloat(rawData.quoteVolume), + baseVolume: parseFloat(rawData.baseVolume), + low: parseFloat(rawData.low), + close: parseFloat(rawData.close), + high: parseFloat(rawData.high), + open: parseFloat(rawData.open), + timestamp: rawData.timestamp, + } as MarketData; +}; export const convertEngineHistory = (rawData: any) => { return { - - _id:rawData._id, - blockNumber:rawData.blockNumber, - transactionId:rawData.transactionId, - timestamp:rawData.timestamp * 1000, - operation:rawData.operation, - from:rawData.from, - to:rawData.to, - symbol:rawData.symbol, - quantity:parseFloat(rawData.quantity), - memo:rawData.memo, - account:rawData.account, - authorperm:rawData.authorperm, - } as HistoryItem -} \ No newline at end of file + _id: rawData._id, + blockNumber: rawData.blockNumber, + transactionId: rawData.transactionId, + timestamp: rawData.timestamp * 1000, + operation: rawData.operation, + from: rawData.from, + to: rawData.to, + symbol: rawData.symbol, + quantity: parseFloat(rawData.quantity), + memo: rawData.memo, + account: rawData.account, + authorperm: rawData.authorperm, + } as HistoryItem; +}; diff --git a/src/providers/hive-engine/hiveEngine.ts b/src/providers/hive-engine/hiveEngine.ts index 58453a943..c78a0cc05 100644 --- a/src/providers/hive-engine/hiveEngine.ts +++ b/src/providers/hive-engine/hiveEngine.ts @@ -1,5 +1,3 @@ - - import { EngineContracts, EngineIds, @@ -15,7 +13,12 @@ import { MarketData, HistoryItem, } from './hiveEngine.types'; -import { convertEngineToken, convertRewardsStatus, convertMarketData, convertEngineHistory } from './converters'; +import { + convertEngineToken, + convertRewardsStatus, + convertMarketData, + convertEngineHistory, +} from './converters'; import bugsnapInstance from '../../config/bugsnag'; import ecencyApi from '../../config/ecencyApi'; @@ -26,19 +29,17 @@ import ecencyApi from '../../config/ecencyApi'; */ const PATH_ENGINE_CONTRACTS = '/private-api/engine-api'; -//proxied path for 'https://scot-api.hive-engine.com/'; +// proxied path for 'https://scot-api.hive-engine.com/'; const PATH_ENGINE_REWARDS = '/private-api/engine-reward-api'; -//proxied path for 'https://info-api.tribaldex.com/market/ohlcv'; +// proxied path for 'https://info-api.tribaldex.com/market/ohlcv'; const PATH_ENGINE_CHART = '/private-api/engine-chart-api'; -//sample hive history endpoint call -//docs: https://github.com/hive-engine/ssc_tokens_history/tree/hive#api-usage -//example: https://history.hive-engine.com/accountHistory?account=demo.com&limit=10&offset=10 +// sample hive history endpoint call +// docs: https://github.com/hive-engine/ssc_tokens_history/tree/hive#api-usage +// example: https://history.hive-engine.com/accountHistory?account=demo.com&limit=10&offset=10 const PATH_ENGINE_ACCOUNT_HISTORY = '/private-api/engine-account-history'; - - export const fetchTokenBalances = (account: string): Promise => { const data: EngineRequestPayload = { jsonrpc: JSON_RPC.RPC_2, @@ -47,13 +48,14 @@ export const fetchTokenBalances = (account: string): Promise => contract: EngineContracts.TOKENS, table: EngineTables.BALANCES, query: { - account: account, + account, }, }, id: EngineIds.ONE, }; - return ecencyApi.post(PATH_ENGINE_CONTRACTS, data) + return ecencyApi + .post(PATH_ENGINE_CONTRACTS, data) .then((r) => r.data.result) .catch((e) => { return []; @@ -86,17 +88,14 @@ export const fetchHiveEngineTokenBalances = async ( account: string, ): Promise> => { try { - const balances = await fetchTokenBalances(account); const symbols = balances.map((t) => t.symbol); const tokens = await fetchTokens(symbols); const metrices = await fetchMetics(symbols); - const unclaimed = await fetchUnclaimedRewards(account) - + const unclaimed = await fetchUnclaimedRewards(account); return balances.map((balance) => { - const token = tokens.find((t) => t.symbol == balance.symbol); const metrics = metrices.find((t) => t.symbol == balance.symbol); const pendingRewards = unclaimed.find((t) => t.symbol == balance.symbol); @@ -109,11 +108,8 @@ export const fetchHiveEngineTokenBalances = async ( } }; - - export const fetchMetics = async (tokens?: string[]) => { try { - const data = { jsonrpc: JSON_RPC.RPC_2, method: Methods.FIND, @@ -122,94 +118,101 @@ export const fetchMetics = async (tokens?: string[]) => { table: EngineTables.METRICS, query: { symbol: { $in: tokens }, - } + }, }, - id: EngineIds.ONE + id: EngineIds.ONE, }; - const response = await ecencyApi.post(PATH_ENGINE_CONTRACTS, data) + const response = await ecencyApi.post(PATH_ENGINE_CONTRACTS, data); if (!response.data.result) { - throw new Error("No metric data returned") + throw new Error('No metric data returned'); } - return response.data.result as EngineMetric[] - + return response.data.result as EngineMetric[]; } catch (err) { console.warn('Failed to get engine metrices', err); bugsnapInstance.notify(err); throw err; } -} - +}; export const fetchUnclaimedRewards = async (account: string): Promise => { try { const response = await ecencyApi.get(`${PATH_ENGINE_REWARDS}/${account}`, { - params:{hive:1} - }) - const rawData = Object.values(response.data) + params: { hive: 1 }, + }); + const rawData = Object.values(response.data); if (!rawData || rawData.length === 0) { - throw new Error("No rewards data returned"); + throw new Error('No rewards data returned'); } const data = rawData.map(convertRewardsStatus); - const filteredData = data.filter(item => item && item.pendingToken > 0) + const filteredData = data.filter((item) => item && item.pendingToken > 0); console.log('unclaimed engine rewards data', filteredData); return filteredData; - } catch (err) { - console.warn("failed ot get unclaimed engine rewards", err) + console.warn('failed ot get unclaimed engine rewards', err); bugsnapInstance.notify(err); return []; } }; -export const fetchEngineMarketData = async (symbol: any, vsCurrency:string = 'usd', days:number = 0, interval = 'daily') => { +export const fetchEngineMarketData = async ( + symbol: any, + vsCurrency = 'usd', + days = 0, + interval = 'daily', +) => { try { const response = await ecencyApi.get(PATH_ENGINE_CHART, { - params: { symbol, interval } + params: { symbol, interval }, }); const rawData = response?.data; - if(!rawData){ - throw new Error("No data returned"); + if (!rawData) { + throw new Error('No data returned'); } - const data:MarketData[] = rawData.map(convertMarketData); + const data: MarketData[] = rawData.map(convertMarketData); return days > 1 && data.length > days ? data.slice(data.length - days) : data; } catch (err) { bugsnapInstance.notify(err); - console.warn("failed to get chart data", err.message); - return [] + console.warn('failed to get chart data', err.message); + return []; } }; - - export const fetchEngineAccountHistory = async (username:string , symbol:string , startIndex:number = 0, limit:number = 20) => { +export const fetchEngineAccountHistory = async ( + username: string, + symbol: string, + startIndex = 0, + limit = 20, +) => { try { - const response = await ecencyApi.get(PATH_ENGINE_ACCOUNT_HISTORY, {params:{ - account:username, - symbol:symbol, - limit, - offset: limit * startIndex - }}) + const response = await ecencyApi.get(PATH_ENGINE_ACCOUNT_HISTORY, { + params: { + account: username, + symbol, + limit, + offset: limit * startIndex, + }, + }); const rawData = response?.data; - if(!rawData){ - throw new Error("No data returned"); + if (!rawData) { + throw new Error('No data returned'); } - const data:HistoryItem[] = rawData.map(convertEngineHistory); + const data: HistoryItem[] = rawData.map(convertEngineHistory); return data; } catch (err) { bugsnapInstance.notify(err); - console.warn("failed to get engine account history", err.message); - return [] + console.warn('failed to get engine account history', err.message); + return []; } - } - +}; diff --git a/src/providers/hive-engine/hiveEngine.types.ts b/src/providers/hive-engine/hiveEngine.types.ts index c5e7d8447..46db62fb5 100644 --- a/src/providers/hive-engine/hiveEngine.types.ts +++ b/src/providers/hive-engine/hiveEngine.types.ts @@ -9,7 +9,7 @@ export enum JSON_RPC { export enum EngineContracts { TOKENS = 'tokens', - MARKET = 'market' + MARKET = 'market', } export enum EngineActions { @@ -17,10 +17,9 @@ export enum EngineActions { DELEGATE = 'delegate', UNDELEGATE = 'undelegate', UNSTAKE = 'unstake', - STAKE = 'stake' + STAKE = 'stake', } - export enum EngineTables { BALANCES = 'balances', DELEGATIONS = 'delegations', @@ -32,7 +31,6 @@ export enum EngineIds { ONE = '1', } - export interface TokenBalance { symbol: string; balance: string; @@ -79,7 +77,7 @@ export interface HiveEngineToken { tokenPrice?: number; percentChange?: number; unclaimedBalance: string; - volume24h?:number + volume24h?: number; } export interface TokenMetadata { @@ -95,21 +93,18 @@ export interface TokenStatus { pendingRewards: number; } - - export interface EngineMetric { - _id: number + _id: number; highestBid: string; lastDayPrice: string; lastDayPriceExpiration: number; lastPrice: string; lowestAsk: string; - priceChangeHive:string; - priceChangePercent:string; + priceChangeHive: string; + priceChangePercent: string; symbol: string; volume: string; volumeExpiration: number; - } interface EngineQuery { @@ -130,105 +125,102 @@ export interface EngineRequestPayload { id: EngineIds; } - - export interface EngineActionPayload { - to:string, - symbol:string, - quantity:string, - memo?:string + to: string; + symbol: string; + quantity: string; + memo?: string; } export interface EngineActionJSON { - contractName:EngineContracts; - contractAction:EngineActions; + contractName: EngineContracts; + contractAction: EngineActions; contractPayload: EngineActionPayload; } - export interface MarketData { - quoteVolume:number; - baseVolume:number; - low:number; - close:number; - high:number; - open:number; - timestamp:number; + quoteVolume: number; + baseVolume: number; + low: number; + close: number; + high: number; + open: number; + timestamp: number; } export interface HistoryItem { -_id:string; -blockNumber:number; -transactionId:string; -timestamp:number; -operation:EngineOperations; -from:string; -to:string; -symbol:string; -quantity:number; -memo:string; -account:string; -authorperm?:string; + _id: string; + blockNumber: number; + transactionId: string; + timestamp: number; + operation: EngineOperations; + from: string; + to: string; + symbol: string; + quantity: number; + memo: string; + account: string; + authorperm?: string; } export enum EngineOperations { - TOKENS_CREATE = "tokens_create", - TOKENS_ISSUE = "tokens_issue", - TOKENS_TRANSFER = "tokens_transfer", - TOKENS_TRANSFER_TO_CONTRACT = "tokens_transferToContract", - TOKENS_TRANSFER_FROM_CONTRACT = "tokens_transferFromContract", - TOKENS_UPDATE_PRECISION = "tokens_updatePrecision", - TOKENS_UPDATE_URL = "tokens_updateUrl", - TOKENS_UPDATE_METADATA = "tokens_updateMetadata", - TOKENS_TRANSFER_OWNERSHIP = "tokens_transferOwnership", - TOKENS_ENABLE_STAKING = "tokens_enableStaking", - TOKENS_ENABLE_DELEGATION = "tokens_enableDelegation", - TOKENS_STAKE = "tokens_stake", - TOKENS_UNSTAKE_START = "tokens_unstakeStart", - TOKENS_UNSTAKE_DONE = "tokens_unstakeDone", - TOKENS_CANCEL_UNSTAKE = "tokens_cancelUnstake", - TOKENS_DELEGATE = "tokens_delegate", - TOKENS_UNDELEGATE_START = "tokens_undelegateStart", - TOKENS_UNDELEGATE_DONE = "tokens_undelegateDone", - TOKENS_TRANSFER_FEE = "tokens_transferFee", - MARKET_CANCEL = "market_cancel", - MARKET_PLACE_ORDER = "market_placeOrder", - MARKET_EXPIRE = "market_expire", - MARKET_BUY = "market_buy", - MARKET_BUY_REMAINING = "market_buyRemaining", - MARKET_SELL = "market_sell", - MARKET_SELL_REMAINING = "market_sellRemaining", - MARKET_CLOSE = "market_close", - MINING_LOTTERY = "mining_lottery", - WITNESSES_PROPOSE_ROUND = "witnesses_proposeRound", - HIVEPEGGED_BUY = "hivepegged_buy", - HIVEPEGGED_WITHDRAW = "hivepegged_withdraw", - INFLATION_ISSUE_NEW_TOKENS = "inflation_issueNewTokens", - NFT_TRANSFER = "nft_transfer", - NFT_ISSUE = "nft_issue", - NFT_ISSUE_MULTIPLE = "nft_issueMultiple", - NFT_BURN = "nft_burn", - NFT_DELEGATE = "nft_delegate", - NFT_UNDELEGATE = "nft_undelegate", - NFT_UNDELEGATE_DONE = "nft_undelegateDone", - NFT_ENABLE_DELEGATION = "nft_enableDelegation", - NFT_CREATE = "nft_create", - NFT_ADD_AUTHORIZED_ISSUING_ACCOUNTS = "nft_addAuthorizedIssuingAccounts", - NFT_SET_GROUP_BY = "nft_setGroupBy", - NFT_SET_PROPERTIES = "nft_setProperties", - NFT_ADD_PROPERTY = "nft_addProperty", - NFT_SET_PROPERTY_PERMISSIONS = "nft_setPropertyPermissions", - NFT_UPDATE_PROPERTY_DEFINITION = "nft_updatePropertyDefinition", - NFT_UPDATE_URL = "nft_updateUrl", - NFT_UPDATE_METADATA = "nft_updateMetadata", - NFT_UPDATE_NAME = "nft_updateName", - NFT_UPDATE_ORG_NAME = "nft_updateOrgName", - NFT_UPDATE_PRODUCT_NAME = "nft_updateProductName", - NFT_TRANSFER_FEE = "nft_transferFee", - NFTMARKET_BUY = "nftmarket_buy", - NFTMARKET_TRANSFER_FEE = "nftmarket_transferFee", - NFTMARKET_SELL = "nftmarket_sell", - NFTMARKET_CANCEL = "nftmarket_cancel", - NFTMARKET_CHANGE_PRICE = "nftmarket_changePrice", - NFTMARKET_ENABLE_MARKET = "nftmarket_enableMarket" + TOKENS_CREATE = 'tokens_create', + TOKENS_ISSUE = 'tokens_issue', + TOKENS_TRANSFER = 'tokens_transfer', + TOKENS_TRANSFER_TO_CONTRACT = 'tokens_transferToContract', + TOKENS_TRANSFER_FROM_CONTRACT = 'tokens_transferFromContract', + TOKENS_UPDATE_PRECISION = 'tokens_updatePrecision', + TOKENS_UPDATE_URL = 'tokens_updateUrl', + TOKENS_UPDATE_METADATA = 'tokens_updateMetadata', + TOKENS_TRANSFER_OWNERSHIP = 'tokens_transferOwnership', + TOKENS_ENABLE_STAKING = 'tokens_enableStaking', + TOKENS_ENABLE_DELEGATION = 'tokens_enableDelegation', + TOKENS_STAKE = 'tokens_stake', + TOKENS_UNSTAKE_START = 'tokens_unstakeStart', + TOKENS_UNSTAKE_DONE = 'tokens_unstakeDone', + TOKENS_CANCEL_UNSTAKE = 'tokens_cancelUnstake', + TOKENS_DELEGATE = 'tokens_delegate', + TOKENS_UNDELEGATE_START = 'tokens_undelegateStart', + TOKENS_UNDELEGATE_DONE = 'tokens_undelegateDone', + TOKENS_TRANSFER_FEE = 'tokens_transferFee', + MARKET_CANCEL = 'market_cancel', + MARKET_PLACE_ORDER = 'market_placeOrder', + MARKET_EXPIRE = 'market_expire', + MARKET_BUY = 'market_buy', + MARKET_BUY_REMAINING = 'market_buyRemaining', + MARKET_SELL = 'market_sell', + MARKET_SELL_REMAINING = 'market_sellRemaining', + MARKET_CLOSE = 'market_close', + MINING_LOTTERY = 'mining_lottery', + WITNESSES_PROPOSE_ROUND = 'witnesses_proposeRound', + HIVEPEGGED_BUY = 'hivepegged_buy', + HIVEPEGGED_WITHDRAW = 'hivepegged_withdraw', + INFLATION_ISSUE_NEW_TOKENS = 'inflation_issueNewTokens', + NFT_TRANSFER = 'nft_transfer', + NFT_ISSUE = 'nft_issue', + NFT_ISSUE_MULTIPLE = 'nft_issueMultiple', + NFT_BURN = 'nft_burn', + NFT_DELEGATE = 'nft_delegate', + NFT_UNDELEGATE = 'nft_undelegate', + NFT_UNDELEGATE_DONE = 'nft_undelegateDone', + NFT_ENABLE_DELEGATION = 'nft_enableDelegation', + NFT_CREATE = 'nft_create', + NFT_ADD_AUTHORIZED_ISSUING_ACCOUNTS = 'nft_addAuthorizedIssuingAccounts', + NFT_SET_GROUP_BY = 'nft_setGroupBy', + NFT_SET_PROPERTIES = 'nft_setProperties', + NFT_ADD_PROPERTY = 'nft_addProperty', + NFT_SET_PROPERTY_PERMISSIONS = 'nft_setPropertyPermissions', + NFT_UPDATE_PROPERTY_DEFINITION = 'nft_updatePropertyDefinition', + NFT_UPDATE_URL = 'nft_updateUrl', + NFT_UPDATE_METADATA = 'nft_updateMetadata', + NFT_UPDATE_NAME = 'nft_updateName', + NFT_UPDATE_ORG_NAME = 'nft_updateOrgName', + NFT_UPDATE_PRODUCT_NAME = 'nft_updateProductName', + NFT_TRANSFER_FEE = 'nft_transferFee', + NFTMARKET_BUY = 'nftmarket_buy', + NFTMARKET_TRANSFER_FEE = 'nftmarket_transferFee', + NFTMARKET_SELL = 'nftmarket_sell', + NFTMARKET_CANCEL = 'nftmarket_cancel', + NFTMARKET_CHANGE_PRICE = 'nftmarket_changePrice', + NFTMARKET_ENABLE_MARKET = 'nftmarket_enableMarket', } diff --git a/src/providers/hive-trade/hiveTrade.ts b/src/providers/hive-trade/hiveTrade.ts index c0aaefc0f..46a6bbeda 100644 --- a/src/providers/hive-trade/hiveTrade.ts +++ b/src/providers/hive-trade/hiveTrade.ts @@ -70,13 +70,7 @@ export const limitOrderCreate = ( ); }; - -export const limitOrderCancel = ( - currentAccount: any, - pinHash:string, - orderid: number -) => { - +export const limitOrderCancel = (currentAccount: any, pinHash: string, orderid: number) => { const digitPinCode = getDigitPinCode(pinHash); const key = getAnyPrivateKey( { @@ -87,13 +81,13 @@ export const limitOrderCancel = ( if (key) { const privateKey = PrivateKey.fromString(key); - const ops:Operation[] = [ + const ops: Operation[] = [ [ - "limit_order_cancel", + 'limit_order_cancel', { owner: currentAccount.username, - orderid: orderid - } + orderid, + }, ], ]; @@ -113,8 +107,6 @@ export const limitOrderCancel = ( ); }; - - export const generateHsLimitOrderCreatePath = ( currentAccount: any, amountToSell: number, diff --git a/src/providers/hive/dhive.js b/src/providers/hive/dhive.js index a3f0f67a2..05fac84ac 100644 --- a/src/providers/hive/dhive.js +++ b/src/providers/hive/dhive.js @@ -2154,8 +2154,8 @@ export const resolveTransaction = async (parsedTx, parsedParams, signer) => { signers: [signer], preferred_signer: signer, }); - tx.ref_block_num = parseInt(tx.ref_block_num + '', 10); - tx.ref_block_prefix = parseInt(tx.ref_block_prefix + '', 10); + tx.ref_block_num = parseInt(`${tx.ref_block_num}`, 10); + tx.ref_block_prefix = parseInt(`${tx.ref_block_prefix}`, 10); return tx; }; diff --git a/src/providers/hive/hive.types.ts b/src/providers/hive/hive.types.ts index e67675095..4b18d68b3 100644 --- a/src/providers/hive/hive.types.ts +++ b/src/providers/hive/hive.types.ts @@ -111,8 +111,8 @@ export interface SavingsWithdrawRequest { } export interface TransferDataType { - fundType:string, - destination:string - amount: string - memo?:string -} \ No newline at end of file + fundType: string; + destination: string; + amount: string; + memo?: string; +} diff --git a/src/providers/queries/editorQueries.ts b/src/providers/queries/editorQueries.ts index 39b9a8f25..203550347 100644 --- a/src/providers/queries/editorQueries.ts +++ b/src/providers/queries/editorQueries.ts @@ -33,7 +33,7 @@ interface MediaUploadVars { addToUploads: boolean; } -/** GET QUERIES **/ +/** GET QUERIES * */ export const useMediaQuery = () => { const intl = useIntl(); @@ -57,7 +57,7 @@ export const useSnippetsQuery = () => { }); }; -/** ADD UPDATE MUTATIONS **/ +/** ADD UPDATE MUTATIONS * */ export const useAddToUploadsMutation = () => { const intl = useIntl(); @@ -71,7 +71,7 @@ export const useAddToUploadsMutation = () => { }, onError: (error) => { if (error.toString().includes('code 409')) { - //means image ware already preset, refresh to get updated order + // means image ware already preset, refresh to get updated order queryClient.invalidateQueries([QUERIES.MEDIA.GET]); } else { dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); @@ -234,7 +234,7 @@ export const useSnippetsMutation = () => { ); }; -/** DELETE MUTATIONS **/ +/** DELETE MUTATIONS * */ export const useMediaDeleteMutation = () => { const queryClient = useQueryClient(); diff --git a/src/providers/queries/index.ts b/src/providers/queries/index.ts index dd6f859a0..c060f5fd1 100644 --- a/src/providers/queries/index.ts +++ b/src/providers/queries/index.ts @@ -10,7 +10,7 @@ export const initQueryClient = () => { }); const client = new QueryClient({ - //Query client configurations go here... + // Query client configurations go here... defaultOptions: { queries: { cacheTime: 1000 * 60 * 60 * 24 * 6, // 7 days cache timer @@ -18,34 +18,32 @@ export const initQueryClient = () => { }, }); - - - - const _shouldDehdrateQuery = (query:Query) => { + const _shouldDehdrateQuery = (query: Query) => { const _isSuccess = query.state.status === 'success'; - if(_isSuccess){ - //Cherry pick whihc queries to dehydrate for persistance - switch(query.queryKey[0]){ + if (_isSuccess) { + // Cherry pick whihc queries to dehydrate for persistance + switch (query.queryKey[0]) { case QUERIES.WAVES.GET: - return query.queryKey[3] === 0 //only dehydrate first page of waves + return query.queryKey[3] === 0; // only dehydrate first page of waves case QUERIES.NOTIFICATIONS.GET: - return query.queryKey[2] === '' //only dehydrate first page of notifications + return query.queryKey[2] === ''; // only dehydrate first page of notifications default: return true; } } - - console.log("status error for dehydration", query.queryKey) + + console.log('status error for dehydration', query.queryKey); return false; - } + }; return { client, persistOptions: { - persister: asyncStoragePersister, dehydrateOptions: { - shouldDehydrateQuery: _shouldDehdrateQuery - } + persister: asyncStoragePersister, + dehydrateOptions: { + shouldDehydrateQuery: _shouldDehdrateQuery, + }, }, } as PersistQueryClientProviderProps; }; @@ -56,4 +54,4 @@ export * from './editorQueries'; export * from './pointQueries'; export * from './postQueries'; export * from './walletQueries'; -export * from './leaderboardQueries'; \ No newline at end of file +export * from './leaderboardQueries'; diff --git a/src/providers/queries/postQueries/postQueries.ts b/src/providers/queries/postQueries/postQueries.ts index b7cffbe5e..2afa4ac29 100644 --- a/src/providers/queries/postQueries/postQueries.ts +++ b/src/providers/queries/postQueries/postQueries.ts @@ -122,7 +122,7 @@ export const useDiscussionQuery = (_author?: string, _permlink?: string) => { ); useEffect(() => { - const _data = injectPostCache(query.data, cachedComments, cachedVotes, lastCacheUpdate); + const _data = injectPostCache(query.data, cachedComments, cachedVotes, lastCacheUpdate); setData(_data); }, [query.data, cachedComments, cachedVotes]); @@ -130,7 +130,6 @@ export const useDiscussionQuery = (_author?: string, _permlink?: string) => { restructureData(); }, [data]); - // traverse discussion collection to curate sections const restructureData = async () => { const MAX_THREAD_LEVEL = 3; diff --git a/src/providers/queries/postQueries/wavesQueries.ts b/src/providers/queries/postQueries/wavesQueries.ts index eb7db8559..3ed4e3010 100644 --- a/src/providers/queries/postQueries/wavesQueries.ts +++ b/src/providers/queries/postQueries/wavesQueries.ts @@ -1,33 +1,27 @@ - -import { - UseMutationOptions, - useMutation, - useQueries, useQueryClient, -} from '@tanstack/react-query'; +import { UseMutationOptions, useMutation, useQueries, useQueryClient } from '@tanstack/react-query'; import { useEffect, useMemo, useRef, useState } from 'react'; import { unionBy, isArray } from 'lodash'; -import { getDiscussionCollection } from '../../hive/dhive'; +import { getDiscussionCollection, getAccountPosts } from '../../hive/dhive'; -import { getAccountPosts } from '../../hive/dhive'; import QUERIES from '../queryKeys'; import { delay } from '../../../utils/editor'; -import { injectPostCache, injectVoteCache, mapDiscussionToThreads } from '../../../utils/postParser'; +import { + injectPostCache, + injectVoteCache, + mapDiscussionToThreads, +} from '../../../utils/postParser'; import { useAppSelector } from '../../../hooks'; - - export const useWavesQuery = (host: string) => { - const queryClient = useQueryClient(); - const cache = useAppSelector(state => state.cache); - const mutes = useAppSelector(state => state.account.currentAccount.mutes); + const cache = useAppSelector((state) => state.cache); + const mutes = useAppSelector((state) => state.account.currentAccount.mutes); const cacheRef = useRef(cache); - const cachedVotes = cache.votesCollection - const lastCacheUpdate = cache.lastUpdate - + const cachedVotes = cache.votesCollection; + const lastCacheUpdate = cache.lastUpdate; const [isRefreshing, setIsRefreshing] = useState(false); const [isLoading, setIsLoading] = useState(true); @@ -35,102 +29,99 @@ export const useWavesQuery = (host: string) => { const wavesIndexCollection = useRef<{ [key: string]: string }>({}); - const _initialContainerPermlinks = useMemo(() => - queryClient.getQueryData([QUERIES.WAVES.INITIAL_CONTAINERS, host]) || [], []); + const _initialContainerPermlinks = useMemo( + () => queryClient.getQueryData([QUERIES.WAVES.INITIAL_CONTAINERS, host]) || [], + [], + ); const [permlinksBucket, setPermlinksBucket] = useState(_initialContainerPermlinks); - // query initialization const wavesQueries = useQueries({ queries: activePermlinks.map((pagePermlink, index) => ({ - queryKey: [QUERIES.WAVES.GET, host, pagePermlink, index], //index at end is used to track query hydration + queryKey: [QUERIES.WAVES.GET, host, pagePermlink, index], // index at end is used to track query hydration queryFn: () => _fetchWaves(pagePermlink), initialData: [], })), }); - - //hook to update cache reference, - //workaround required since query fucntion do get passed an - //updated copy for states that are not part of query key and contexet while conext is not - //supported by useQueries + // hook to update cache reference, + // workaround required since query fucntion do get passed an + // updated copy for states that are not part of query key and contexet while conext is not + // supported by useQueries useEffect(() => { cacheRef.current = cache; - }, [cache]) + }, [cache]); useEffect(() => { _fetchPermlinks('', true); - }, []) - + }, []); useEffect(() => { - if (!!permlinksBucket.length) { - //if first elements permlinks do not match, means there is a new container, push at first + if (permlinksBucket.length) { + // if first elements permlinks do not match, means there is a new container, push at first if (permlinksBucket[0] !== activePermlinks[0]) { activePermlinks.splice(0, 0, permlinksBucket[0]); } - //permlinks bucket is updated, it needs to be connect with active one to start chain again + // permlinks bucket is updated, it needs to be connect with active one to start chain again else { activePermlinks.push(permlinksBucket[activePermlinks.length]); } setActivePermlinks([...activePermlinks]); } - }, [permlinksBucket]) - - + }, [permlinksBucket]); useEffect(() => { const _latestData = wavesQueries.lastItem?.data; if (!_latestData || _latestData.length < 10) { _fetchNextPage(); } - }, [wavesQueries.lastItem?.data]) - + }, [wavesQueries.lastItem?.data]); useEffect(() => { - //check cache is recently updated and take post path + // check cache is recently updated and take post path if (lastCacheUpdate) { - const _timeElapsed = new Date().getTime() - lastCacheUpdate.updatedAt + const _timeElapsed = new Date().getTime() - lastCacheUpdate.updatedAt; if (lastCacheUpdate.type === 'vote' && _timeElapsed < 5000) { - _injectPostCache(lastCacheUpdate.postPath) + _injectPostCache(lastCacheUpdate.postPath); } } - - }, [lastCacheUpdate]) - + }, [lastCacheUpdate]); const _injectPostCache = async (postPath: string) => { - //using post path get index of query key where that post exists + // using post path get index of query key where that post exists const _containerPermlink = wavesIndexCollection.current[postPath]; - const _containerIndex = activePermlinks.indexOf(_containerPermlink) + const _containerIndex = activePermlinks.indexOf(_containerPermlink); const _voteCache = cachedVotes[postPath]; if (_containerIndex >= 0 && _voteCache) { - //mean data exist, get query data, update query data by finding post and injecting cache + // mean data exist, get query data, update query data by finding post and injecting cache const _qData: any[] | undefined = wavesQueries[_containerIndex].data; if (_qData) { - const _postIndex = _qData.findIndex((item) => lastCacheUpdate.postPath === `${item.author}/${item.permlink}`); + const _postIndex = _qData.findIndex( + (item) => lastCacheUpdate.postPath === `${item.author}/${item.permlink}`, + ); const _post = _qData[_postIndex]; if (_post) { - //inject cache and set query data + // inject cache and set query data const _cPost = injectVoteCache(_post, _voteCache); _qData.splice(_postIndex, 1, _cPost); - queryClient.setQueryData([QUERIES.WAVES.GET, host, _containerPermlink, _containerIndex], [..._qData]); //TODO: use container permlink as well + queryClient.setQueryData( + [QUERIES.WAVES.GET, host, _containerPermlink, _containerIndex], + [..._qData], + ); // TODO: use container permlink as well } } } - } - - + }; const _fetchPermlinks = async (startPermlink = '', refresh = false) => { setIsLoading(true); try { const query: any = { account: host, - start_author: !!startPermlink ? host : '', + start_author: startPermlink ? host : '', start_permlink: startPermlink, limit: 5, observer: '', @@ -139,56 +130,53 @@ export const useWavesQuery = (host: string) => { const result = await getAccountPosts(query); - const _fetchedPermlinks = result.map(post => post.permlink); + const _fetchedPermlinks = result.map((post) => post.permlink); console.log('permlinks fetched', _fetchedPermlinks); - const _permlinksBucket = refresh ? _fetchedPermlinks : [...permlinksBucket, ..._fetchedPermlinks]; + const _permlinksBucket = refresh + ? _fetchedPermlinks + : [...permlinksBucket, ..._fetchedPermlinks]; setPermlinksBucket(_permlinksBucket); if (refresh) { queryClient.setQueryData([QUERIES.WAVES.INITIAL_CONTAINERS, host], _permlinksBucket); - //precautionary delay of 200ms to let state update before concluding promise, - //it is effective for waves refresh routine. - await delay(200) + // precautionary delay of 200ms to let state update before concluding promise, + // it is effective for waves refresh routine. + await delay(200); } - - } catch (err) { - console.warn("failed to fetch waves permlinks"); + console.warn('failed to fetch waves permlinks'); } - setIsLoading(false) - - } + setIsLoading(false); + }; const _fetchWaves = async (pagePermlink: string) => { console.log('fetching waves from:', host, pagePermlink); const response = await getDiscussionCollection(host, pagePermlink); - //inject cache here... + // inject cache here... const _cachedComments = cacheRef.current.commentsCollection; const _cachedVotes = cacheRef.current.votesCollection; - const _lastCacheUpdate = cacheRef.current.lastCacheUpdate + const _lastCacheUpdate = cacheRef.current.lastCacheUpdate; const _cResponse = injectPostCache(response, _cachedComments, _cachedVotes, _lastCacheUpdate); const _threadedComments = await mapDiscussionToThreads(_cResponse, host, pagePermlink, 1); if (!_threadedComments) { - throw new Error("Failed to parse waves"); + throw new Error('Failed to parse waves'); } - _threadedComments.sort((a, b) => new Date(a.created) > new Date(b.created) ? -1 : 1); + _threadedComments.sort((a, b) => (new Date(a.created) > new Date(b.created) ? -1 : 1)); _threadedComments.forEach((item) => { - wavesIndexCollection.current[`${item.author}/${item.permlink}`] = pagePermlink - }) + wavesIndexCollection.current[`${item.author}/${item.permlink}`] = pagePermlink; + }); console.log('new waves fetched', _threadedComments); return _threadedComments || []; }; - - const _fetchNextPage = () => { const lastPage = wavesQueries.lastItem; @@ -199,17 +187,15 @@ export const useWavesQuery = (host: string) => { const _nextPagePermlink = permlinksBucket[activePermlinks.length]; if (_nextPagePermlink && !activePermlinks.includes(_nextPagePermlink)) { - console.log("updating next page permlink", _nextPagePermlink) + console.log('updating next page permlink', _nextPagePermlink); activePermlinks.push(_nextPagePermlink); setActivePermlinks([...activePermlinks]); } else { - console.log("fetching new containers", permlinksBucket.lastItem) - _fetchPermlinks(permlinksBucket.lastItem) + console.log('fetching new containers', permlinksBucket.lastItem); + _fetchPermlinks(permlinksBucket.lastItem); } }; - - const _refresh = async () => { setIsRefreshing(true); setPermlinksBucket([]); @@ -219,38 +205,32 @@ export const useWavesQuery = (host: string) => { setIsRefreshing(false); }; - - - - const _data = unionBy(...wavesQueries.map((query) => query.data), 'url'); - const _filteredData = useMemo(() => - _data.filter(post => isArray(mutes) ? mutes.indexOf(post?.author) < 0 : true), - [mutes, _data]) - - - + const _filteredData = useMemo( + () => _data.filter((post) => (isArray(mutes) ? mutes.indexOf(post?.author) < 0 : true)), + [mutes, _data], + ); const _lastestWavesFetch = async () => { - await _fetchPermlinks('', true); - const _prevLatestWave = _filteredData[0] + const _prevLatestWave = _filteredData[0]; const _firstQuery = wavesQueries[0]; - if(!_firstQuery){ + if (!_firstQuery) { return []; } const queryResponse = await _firstQuery.refetch(); - const _newData:any[] = queryResponse.data || []; + const _newData: any[] = queryResponse.data || []; - //check if new waves are available - const _lastIndex = _newData?.findIndex(item => - ( item.author + item.permlink === _prevLatestWave.author + _prevLatestWave.permlink)); + // check if new waves are available + const _lastIndex = _newData?.findIndex( + (item) => item.author + item.permlink === _prevLatestWave.author + _prevLatestWave.permlink, + ); - let _newWaves:any[] = [] + let _newWaves: any[] = []; if (_lastIndex && _lastIndex !== 0) { if (_lastIndex < 0) { _newWaves = _newData?.slice(0, 5) || []; @@ -259,10 +239,8 @@ export const useWavesQuery = (host: string) => { } } - - return _newWaves - } - + return _newWaves; + }; return { data: _filteredData, @@ -274,26 +252,21 @@ export const useWavesQuery = (host: string) => { }; }; - - - - export const usePublishWaveMutation = () => { - const queryClient = useQueryClient(); // id is options, if no id is provided program marks all notifications as read; const _mutationFn = async (cachePostData: any) => { - //TODO: lates port wave publishing here or introduce post publishing mutation; - if (cachePostData) { //TODO: expand to check multiple wave hosts;{ + // TODO: lates port wave publishing here or introduce post publishing mutation; + if (cachePostData) { + // TODO: expand to check multiple wave hosts;{ const _host = cachePostData.parent_author; console.log('returning waves host', _host); return _host; } - throw new Error("invalid mutations data") - + throw new Error('invalid mutations data'); }; const _options: UseMutationOptions = { @@ -314,11 +287,10 @@ export const usePublishWaveMutation = () => { queryData.splice(0, 0, cacheCommentData); queryClient.setQueryData(_queryKey, queryData); } - }, onSuccess: async (host) => { - //TODO: get first container permlink here from initial containers + // TODO: get first container permlink here from initial containers const queriesData = queryClient.getQueriesData([QUERIES.WAVES.INITIAL_CONTAINERS, host]); const _queryKey = queriesData[0][0]; queryClient.invalidateQueries(_queryKey); @@ -328,8 +300,6 @@ export const usePublishWaveMutation = () => { return useMutation(_mutationFn, _options); }; - - export const fetchLatestWavesContainer = async (host) => { const query: any = { account: host, @@ -346,8 +316,8 @@ export const fetchLatestWavesContainer = async (host) => { console.log('lates waves post', host, _latestPost); if (!_latestPost) { - throw new Error("Lates waves container could be not fetched"); + throw new Error('Lates waves container could be not fetched'); } return _latestPost; -} +}; diff --git a/src/providers/queries/queryKeys.ts b/src/providers/queries/queryKeys.ts index 9d97a381d..b68a4af4a 100644 --- a/src/providers/queries/queryKeys.ts +++ b/src/providers/queries/queryKeys.ts @@ -30,8 +30,8 @@ const QUERIES = { }, WAVES: { GET: 'QUERY_GET_WAVES', - INITIAL_CONTAINERS: 'QUERY_DATA_INITIAL_CONTAINERS' - } + INITIAL_CONTAINERS: 'QUERY_DATA_INITIAL_CONTAINERS', + }, }; export default QUERIES; diff --git a/src/redux/actions/uiAction.ts b/src/redux/actions/uiAction.ts index a4298513d..54a9e0e47 100644 --- a/src/redux/actions/uiAction.ts +++ b/src/redux/actions/uiAction.ts @@ -99,10 +99,10 @@ export const setLockedOrientation = (payload: string) => ({ type: SET_LOCKED_ORIENTATION, }); -export const showReplyModal = ({mode, parentPost}:PostEditorModalData) => ({ +export const showReplyModal = ({ mode, parentPost }: PostEditorModalData) => ({ payload: { mode: mode || 'comment', - parentPost + parentPost, } as PostEditorModalData, type: SHOW_REPLY_MODAL, }); diff --git a/src/redux/actions/walletActions.ts b/src/redux/actions/walletActions.ts index 4f91ddfcf..96ad77b53 100644 --- a/src/redux/actions/walletActions.ts +++ b/src/redux/actions/walletActions.ts @@ -63,7 +63,7 @@ export const fetchCoinQuotes = () => (dispatch, getState) => { }; export const fetchAndSetCoinsData = - (refresh: boolean = false) => + (refresh = false) => async (dispatch: AppDispatch, getState: RootState) => { const coins = getState().wallet.selectedCoins; const { quotes } = getState().wallet; diff --git a/src/redux/reducers/uiReducer.ts b/src/redux/reducers/uiReducer.ts index d355d5405..a20bc0341 100644 --- a/src/redux/reducers/uiReducer.ts +++ b/src/redux/reducers/uiReducer.ts @@ -20,10 +20,9 @@ import { } from '../constants/constants'; import { orientations } from '../constants/orientationsConstants'; - export interface PostEditorModalData { - mode:'wave'|'comment'|'post', - parentPost?:any + mode: 'wave' | 'comment' | 'post'; + parentPost?: any; } interface UiState { @@ -153,8 +152,8 @@ export default function (state = initialState, action): UiState { }; case SHOW_REPLY_MODAL: const _payload = action.payload as PostEditorModalData; - if(_payload.mode === 'comment' && !_payload.parentPost){ - throw new Error("parent post missing for showing post editor modal with comment mode") + if (_payload.mode === 'comment' && !_payload.parentPost) { + throw new Error('parent post missing for showing post editor modal with comment mode'); } return { ...state, diff --git a/src/screens/assetDetails/children/activitiesList.tsx b/src/screens/assetDetails/children/activitiesList.tsx index e84bef987..282f25daf 100644 --- a/src/screens/assetDetails/children/activitiesList.tsx +++ b/src/screens/assetDetails/children/activitiesList.tsx @@ -2,12 +2,12 @@ import React, { ComponentType, JSXElementConstructor, ReactElement, useState } f import { useIntl } from 'react-intl'; import { SectionList, Text, RefreshControl, ActivityIndicator } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; +import { useQueryClient } from '@tanstack/react-query'; import { Transaction } from '../../../components'; import { useAppSelector } from '../../../hooks'; import { CoinActivity } from '../../../redux/reducers/walletReducer'; import styles from './children.styles'; import { limitOrderCancel } from '../../../providers/hive-trade/hiveTrade'; -import { useQueryClient } from '@tanstack/react-query'; import QUERIES from '../../../providers/queries/queryKeys'; import TransferTypes from '../../../constants/transferTypes'; diff --git a/src/screens/assetDetails/children/children.styles.ts b/src/screens/assetDetails/children/children.styles.ts index 5430b74c9..bc63df4e4 100644 --- a/src/screens/assetDetails/children/children.styles.ts +++ b/src/screens/assetDetails/children/children.styles.ts @@ -9,8 +9,8 @@ export default EStyleSheet.create({ overflow: 'hidden', backgroundColor: '$primaryLightBackground', } as ViewStyle, - iconContainer:{ - marginRight:8 + iconContainer: { + marginRight: 8, } as ViewStyle, basicsContainer: { alignItems: 'center', @@ -18,8 +18,8 @@ export default EStyleSheet.create({ } as ViewStyle, coinTitleContainer: { flexDirection: 'row', - alignItems:'center', - marginTop:8 + alignItems: 'center', + marginTop: 8, } as ViewStyle, textCoinTitle: { color: '$primaryBlack', @@ -98,10 +98,8 @@ export default EStyleSheet.create({ paddingHorizontal: 16, } as ViewStyle, - //COIN ACTIONS STYLES - actionBtnContainer: { - - } as ViewStyle, + // COIN ACTIONS STYLES + actionBtnContainer: {} as ViewStyle, actionsContainer: { flexDirection: 'row', flexWrap: 'wrap', diff --git a/src/screens/assetDetails/children/coinBasics.tsx b/src/screens/assetDetails/children/coinBasics.tsx index b4d18aa6c..f9a1409bb 100644 --- a/src/screens/assetDetails/children/coinBasics.tsx +++ b/src/screens/assetDetails/children/coinBasics.tsx @@ -66,12 +66,9 @@ export const CoinBasics = ({ }; const _renderExtraData = (args: DataPair, index: number) => { - const label = intl.formatMessage( { id: `wallet.${args.dataKey || args.labelId}` }, - args.subValue - ? { subValue: args.subValue } - : undefined + args.subValue ? { subValue: args.subValue } : undefined, ); const _onPress = () => { diff --git a/src/screens/assetDetails/children/coinChart.tsx b/src/screens/assetDetails/children/coinChart.tsx index a952d1ee1..1f9ce9b99 100644 --- a/src/screens/assetDetails/children/coinChart.tsx +++ b/src/screens/assetDetails/children/coinChart.tsx @@ -31,11 +31,7 @@ export const CoinChart = ({ coinId, isEngine }: CoinChartProps) => { ); setChartData(marketData.map((item) => item.close)); } else { - const marketData = await fetchMarketChart( - coinId, - currency.currency, - days - ); + const marketData = await fetchMarketChart(coinId, currency.currency, days); setChartData(marketData.prices.map((item) => item.yValue)); } }; diff --git a/src/screens/assetDetails/children/coinSummary.tsx b/src/screens/assetDetails/children/coinSummary.tsx index b120c6d23..c9440386a 100644 --- a/src/screens/assetDetails/children/coinSummary.tsx +++ b/src/screens/assetDetails/children/coinSummary.tsx @@ -27,7 +27,7 @@ export const CoinSummary = ({ const valuePairs = [ { dataKey: 'amount_desc', - value: balance.toFixed(precision ? precision : 3), + value: balance.toFixed(precision || 3), }, ] as DataPair[]; diff --git a/src/screens/assetDetails/children/delegationsModal.tsx b/src/screens/assetDetails/children/delegationsModal.tsx index 257db8b3f..af8a23a0a 100644 --- a/src/screens/assetDetails/children/delegationsModal.tsx +++ b/src/screens/assetDetails/children/delegationsModal.tsx @@ -52,9 +52,9 @@ export const DelegationsModal = forwardRef(({}, ref) => { } }, [mode, showModal]); - const _getVestingDelegations = async (startUsername: string = '') => { + const _getVestingDelegations = async (startUsername = '') => { let resData: any = []; - let limit = 1000; + const limit = 1000; const response = await getVestingDelegations(currentAccount.username, startUsername, limit); resData = response.map( @@ -132,7 +132,7 @@ export const DelegationsModal = forwardRef(({}, ref) => { const title = intl.formatMessage({ id: `wallet.${mode}` }); const _renderItem = ({ item, index }: { item: DelegationItem; index: number }) => { - const value = vestsToHp(item.vestingShares, globalProps.hivePerMVests).toFixed(3) + ' HP'; + const value = `${vestsToHp(item.vestingShares, globalProps.hivePerMVests).toFixed(3)} HP`; const timeString = new Date(item.timestamp).toDateString(); const subRightText = mode === MODES.DELEGATEED && intl.formatMessage({ id: 'wallet.tap_update' }); diff --git a/src/screens/assetDetails/children/rangeSelector.tsx b/src/screens/assetDetails/children/rangeSelector.tsx index 1b853e164..efc5115b4 100644 --- a/src/screens/assetDetails/children/rangeSelector.tsx +++ b/src/screens/assetDetails/children/rangeSelector.tsx @@ -15,33 +15,34 @@ interface RangeSelectorProps { } export const RangeSelector = ({ range, minRange, onRangeChange }: RangeSelectorProps) => { - const _onSelection = (range: number) => { console.log('selection', range); onRangeChange(range); }; - const _renderRangeButtons = FILTERS.filter((item) => item.value >= minRange).map((item: RangeOption) => ( - _onSelection(item.value)}> - - item.value >= minRange).map( + (item: RangeOption) => ( + _onSelection(item.value)}> + - {item.label} - - - - )); + + {item.label} + + + + ), + ); return {_renderRangeButtons}; }; diff --git a/src/screens/assetsSelect/styles/tokensSelectModa.styles.ts b/src/screens/assetsSelect/styles/tokensSelectModa.styles.ts index d97eac36b..c66435721 100644 --- a/src/screens/assetsSelect/styles/tokensSelectModa.styles.ts +++ b/src/screens/assetsSelect/styles/tokensSelectModa.styles.ts @@ -3,7 +3,7 @@ import EStyleSheet from 'react-native-extended-stylesheet'; import getWindowDimensions from '../../../utils/getWindowDimensions'; export default EStyleSheet.create({ - modalStyle:{ + modalStyle: { flex: 1, backgroundColor: '$primaryBackgroundColor', margin: 0, @@ -23,7 +23,7 @@ export default EStyleSheet.create({ } as ViewStyle, scrollContainer: { - flex:1, + flex: 1, marginTop: 16, marginBottom: 16, } as ViewStyle, @@ -35,33 +35,30 @@ export default EStyleSheet.create({ } as TextStyle, modalContainer: { - flex:1, + flex: 1, marginBottom: 44, paddingHorizontal: 24, alignItems: 'center', justifyContent: 'space-between', - } as ViewStyle, - sectionTextStyle : { - color:'$primaryBlack', + sectionTextStyle: { + color: '$primaryBlack', fontSize: 16, marginHorizontal: 16, - marginVertical:4, - + marginVertical: 4, } as TextStyle, - sectionSubTextStyle : { - color:'$iconColor', + sectionSubTextStyle: { + color: '$iconColor', fontSize: 18, marginHorizontal: 16, - marginVertical:16, - alignSelf:'center' - + marginVertical: 16, + alignSelf: 'center', } as TextStyle, - dragBtnContainer:{ - padding:8 + dragBtnContainer: { + padding: 8, } as ViewStyle, title: { @@ -83,12 +80,12 @@ export default EStyleSheet.create({ btnText: { color: '$pureWhite', - textTransform: 'uppercase' + textTransform: 'uppercase', } as TextStyle, - assetIconContainer:{ - width:32, - marginLeft:16 + assetIconContainer: { + width: 32, + marginLeft: 16, }, button: { diff --git a/src/screens/backupKeysScreen/backupKeysScreen.tsx b/src/screens/backupKeysScreen/backupKeysScreen.tsx index 89d91232a..1dc633954 100644 --- a/src/screens/backupKeysScreen/backupKeysScreen.tsx +++ b/src/screens/backupKeysScreen/backupKeysScreen.tsx @@ -2,6 +2,7 @@ import React, { Fragment, useState, useEffect, useRef } from 'react'; import { useIntl } from 'react-intl'; import { ScrollView, Text, TouchableOpacity, View } from 'react-native'; import { gestureHandlerRootHOC } from 'react-native-gesture-handler'; +import get from 'lodash/get'; import { BasicHeader, TextBoxWithCopy } from '../../components'; import { useAppSelector } from '../../hooks'; import { getDigitPinCode } from '../../providers/hive/dhive'; @@ -13,7 +14,6 @@ import styles from './backupKeysScreenStyles'; // utils import { decryptKey } from '../../utils/crypto'; -import get from 'lodash/get'; const BackupKeysScreen = () => { const intl = useIntl(); diff --git a/src/screens/backupKeysScreen/importPrivateKeyModal.tsx b/src/screens/backupKeysScreen/importPrivateKeyModal.tsx index d8e3acfdf..5eadda90c 100644 --- a/src/screens/backupKeysScreen/importPrivateKeyModal.tsx +++ b/src/screens/backupKeysScreen/importPrivateKeyModal.tsx @@ -1,13 +1,13 @@ import { View, Text, TouchableOpacity, Alert } from 'react-native'; import React, { forwardRef, useImperativeHandle, useState } from 'react'; import { useIntl } from 'react-intl'; +import { useDispatch } from 'react-redux'; +import EStyleSheet from 'react-native-extended-stylesheet'; import { Modal, TextInput } from '../../components'; import { useAppSelector } from '../../hooks'; -import { useDispatch } from 'react-redux'; // styles import styles from './backupKeysScreenStyles'; -import EStyleSheet from 'react-native-extended-stylesheet'; // redux / providers import { getUpdatedUserKeys } from '../../providers/hive/auth'; diff --git a/src/screens/boost/screen/styles.ts b/src/screens/boost/screen/styles.ts index 464ad4ac4..7ed4df613 100644 --- a/src/screens/boost/screen/styles.ts +++ b/src/screens/boost/screen/styles.ts @@ -5,7 +5,7 @@ export default EStyleSheet.create({ userRibbonContainer: { borderBottomWidth: EStyleSheet.hairlineWidth, borderColor: '$darkGrayBackground', - marginBottom: 0, //without 0 margin, view will start overlapping UserRibbon + marginBottom: 0, // without 0 margin, view will start overlapping UserRibbon paddingBottom: 32, } as ViewStyle, diff --git a/src/screens/drafts/container/draftsContainer.tsx b/src/screens/drafts/container/draftsContainer.tsx index 96e6c7772..da38a1b77 100644 --- a/src/screens/drafts/container/draftsContainer.tsx +++ b/src/screens/drafts/container/draftsContainer.tsx @@ -78,7 +78,7 @@ const DraftsContainer = ({ currentAccount, navigation, route }) => { const _isCloning = isCloningDraft; const _getUpdatedArray = (arr: string[], id: string) => { - let _tempArr = arr.slice(); + const _tempArr = arr.slice(); const index = _tempArr.findIndex((item) => item === id); if (index !== -1) { diff --git a/src/screens/post/screen/postScreen.tsx b/src/screens/post/screen/postScreen.tsx index ac45e2557..0e47dad85 100644 --- a/src/screens/post/screen/postScreen.tsx +++ b/src/screens/post/screen/postScreen.tsx @@ -2,12 +2,12 @@ import React, { useState, useRef, useEffect, useMemo } from 'react'; import { View } from 'react-native'; // Components +import FastImage from 'react-native-fast-image'; import { BasicHeader, IconButton, PostDisplay, PostOptionsModal } from '../../../components'; import styles from '../styles/postScreen.styles'; // Component import { postQueries } from '../../../providers/queries'; -import FastImage from 'react-native-fast-image'; const PostScreen = ({ route }) => { const params = route.params || {}; @@ -22,21 +22,23 @@ const PostScreen = ({ route }) => { const getPostQuery = postQueries.useGetPostQuery(author, permlink, params.content); const getParentPostQuery = postQueries.useGetPostQuery(); - const isWavePost = useMemo(() => getPostQuery.data?.parent_author === 'ecency.waves', [getPostQuery.data]) //TODO: implement a better generic way to avoid parent fetching for waves + const isWavePost = useMemo( + () => getPostQuery.data?.parent_author === 'ecency.waves', + [getPostQuery.data], + ); // TODO: implement a better generic way to avoid parent fetching for waves useEffect(() => { return () => { - //clears FastImage RAM, not disk usage; + // clears FastImage RAM, not disk usage; FastImage.clearMemoryCache(); - } - }, []) + }; + }, []); useEffect(() => { const post = getPostQuery.data; if (post) { - const _fetchParent = post && post.depth > 0 - && post.parent_author && post.parent_permlink - && !isWavePost; + const _fetchParent = + post && post.depth > 0 && post.parent_author && post.parent_permlink && !isWavePost; if (_fetchParent) { getParentPostQuery.setAuthor(post.parent_author); diff --git a/src/screens/settings/container/settingsContainer.tsx b/src/screens/settings/container/settingsContainer.tsx index a8764aa29..c514407b4 100644 --- a/src/screens/settings/container/settingsContainer.tsx +++ b/src/screens/settings/container/settingsContainer.tsx @@ -313,29 +313,33 @@ class SettingsContainer extends Component { navigateTo: ROUTES.SCREENS.BACKUP_KEYS, }); } else { - dispatch(showActionModal({ - title:intl.formatMessage({id:'alert.warning'}), - body:intl.formatMessage({id:'settings.keys_warning'}), - buttons:[{ - text:intl.formatMessage({id:'alert.cancel'}), - onPress:()=>{}, - type:'destructive' - },{ - text:intl.formatMessage({id:'settings.set_pin'}), - onPress:()=>{ - navigation.navigate(ROUTES.SCREENS.PINCODE, { - callback: () => { - this._enableDefaultUnlockPin(true) + dispatch( + showActionModal({ + title: intl.formatMessage({ id: 'alert.warning' }), + body: intl.formatMessage({ id: 'settings.keys_warning' }), + buttons: [ + { + text: intl.formatMessage({ id: 'alert.cancel' }), + onPress: () => {}, + type: 'destructive', + }, + { + text: intl.formatMessage({ id: 'settings.set_pin' }), + onPress: () => { + navigation.navigate(ROUTES.SCREENS.PINCODE, { + callback: () => { + this._enableDefaultUnlockPin(true); + }, + navigateTo: ROUTES.SCREENS.BACKUP_KEYS, + isReset: true, + isOldPinVerified: true, + oldPinCode: Config.DEFAULT_PIN, + }); }, - navigateTo: ROUTES.SCREENS.BACKUP_KEYS, - isReset: true, - isOldPinVerified: true, - oldPinCode: Config.DEFAULT_PIN, - }); - } - }] - })) - + }, + ], + }), + ); } break; diff --git a/src/screens/trade/children/swapTokenContent.tsx b/src/screens/trade/children/swapTokenContent.tsx index d75e8a7e1..44ebb6299 100644 --- a/src/screens/trade/children/swapTokenContent.tsx +++ b/src/screens/trade/children/swapTokenContent.tsx @@ -32,7 +32,6 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }: const dispatch = useAppDispatch(); const navigation = useNavigation(); - const currentAccount = useAppSelector((state) => state.account.currentAccount); const currency = useAppSelector((state) => state.application.currency); @@ -56,12 +55,10 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }: const _fromAssetId = fromAssetSymbol === MarketAsset.HBD ? ASSET_IDS.HBD : ASSET_IDS.HIVE; const _toAssetId = _toAssetSymbol === MarketAsset.HBD ? ASSET_IDS.HBD : ASSET_IDS.HIVE; - // queres const assetsQuery = walletQueries.useAssetsQuery(); const pendingRequestsQuery = walletQueries.usePendingRequestsQuery(_fromAssetId); - // this method makes sure amount is only updated when new order book is fetched after asset change // this avoid wrong from and to swap value on changing source asset const _onAssetChangeComplete = () => { @@ -93,8 +90,7 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }: const _fromAssetData = assetsData[_fromAssetId]; const _balance = _fromAssetData.balance; const _fromFiatPrice = _fromAssetData.currentPrice; - const _toFiatPrice = - assetsData[_toAssetId].currentPrice; + const _toFiatPrice = assetsData[_toAssetId].currentPrice; const _marketFiatPrice = marketPrice * _toFiatPrice; const _toAmountStr = toAmount.toFixed(3); @@ -130,11 +126,12 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }: setFromAmount('0'); }; - const _onSwapSuccess = async (hasPending:boolean) => { - - const _badgeColor = hasPending ? EStyleSheet.value('$primaryBlue') : EStyleSheet.value('$primaryGreen'); - const _badgeIcon = hasPending ? "error-outline" : "check"; - const _titleId = hasPending ? 'trade.swap_pending' : 'trade.swap_successful' + const _onSwapSuccess = async (hasPending: boolean) => { + const _badgeColor = hasPending + ? EStyleSheet.value('$primaryBlue') + : EStyleSheet.value('$primaryGreen'); + const _badgeIcon = hasPending ? 'error-outline' : 'check'; + const _titleId = hasPending ? 'trade.swap_pending' : 'trade.swap_successful'; const _body = hasPending ? intl.formatMessage({ id: 'trade.swap_pending_body' }) : undefined; const headerContent = ( @@ -190,7 +187,7 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }: const _existingPedingCount = pendingRequestsQuery.data?.length || 0; const pendingRequests = await pendingRequestsQuery.refetch(); const _hasPending = pendingRequests.data?.length !== _existingPedingCount; - + onSuccess(); setSwapping(false); _onSwapSuccess(_hasPending); diff --git a/src/screens/trade/children/useSwapCalculator.tsx b/src/screens/trade/children/useSwapCalculator.tsx index e8df0395a..b30f0d5a2 100644 --- a/src/screens/trade/children/useSwapCalculator.tsx +++ b/src/screens/trade/children/useSwapCalculator.tsx @@ -1,11 +1,9 @@ - -import React, { useEffect, useRef, useState } from "react"; -import { MarketAsset, OrdersDataItem } from "../../../providers/hive-trade/hiveTrade.types"; -import bugsnapInstance from "../../../config/bugsnag"; -import { Alert } from "react-native"; -import { getOrderBook } from "../../../providers/hive/dhive"; -import { stripDecimalPlaces } from "../../../utils/number"; - +import React, { useEffect, useRef, useState } from 'react'; +import { Alert } from 'react-native'; +import { MarketAsset, OrdersDataItem } from '../../../providers/hive-trade/hiveTrade.types'; +import bugsnapInstance from '../../../config/bugsnag'; +import { getOrderBook } from '../../../providers/hive/dhive'; +import { stripDecimalPlaces } from '../../../utils/number'; export namespace HiveMarket { interface ProcessingResult { @@ -15,7 +13,7 @@ export namespace HiveMarket { emptyOrderBook?: boolean; } - function calculatePrice(intAmount: number, book: OrdersDataItem[], asset: "hive" | "hbd") { + function calculatePrice(intAmount: number, book: OrdersDataItem[], asset: 'hive' | 'hbd') { let available = book[0][asset] / 1000; let index = 0; while (available < intAmount && book.length > index + 1) { @@ -29,8 +27,8 @@ export namespace HiveMarket { try { return await getOrderBook(); } catch (e) { - bugsnapInstance.notify(e) - Alert.alert("Order book is empty") + bugsnapInstance.notify(e); + Alert.alert('Order book is empty'); } return null; } @@ -39,7 +37,7 @@ export namespace HiveMarket { buyOrderBook: OrdersDataItem[], sellOrderBook: OrdersDataItem[], fromAmount: number, - asset: string + asset: string, ): ProcessingResult { if (buyOrderBook.length <= 0 || sellOrderBook.length <= 0) return { emptyOrderBook: true }; @@ -48,19 +46,19 @@ export namespace HiveMarket { let availableInOrderBook, price = 0; let firstPrice = Infinity; - let toAmount = 0;; + let toAmount = 0; let resultToAmount; if (asset === MarketAsset.HIVE) { availableInOrderBook = buyOrderBook.map((item) => item.hive).reduce((acc, item) => acc + item, 0) / 1000; - price = calculatePrice(fromAmount, buyOrderBook, "hive"); + price = calculatePrice(fromAmount, buyOrderBook, 'hive'); toAmount = fromAmount * price; firstPrice = +buyOrderBook[0].real_price; } else if (asset === MarketAsset.HBD) { availableInOrderBook = sellOrderBook.map((item) => item.hbd).reduce((acc, item) => acc + item, 0) / 1000; - price = calculatePrice(fromAmount, sellOrderBook, "hbd"); + price = calculatePrice(fromAmount, sellOrderBook, 'hbd'); toAmount = fromAmount / price; firstPrice = +sellOrderBook[0].real_price; } @@ -85,7 +83,7 @@ export namespace HiveMarket { book?.bids ?? [], book?.asks ?? [], fromAmount, - asset + asset, ); if (newToAmount) { return newToAmount; @@ -94,7 +92,6 @@ export namespace HiveMarket { } } - export const useSwapCalculator = ( asset: MarketAsset, fromAmount: number, @@ -110,7 +107,6 @@ export const useSwapCalculator = ( const assetRef = useRef(asset); - let updateInterval: any; useEffect(() => { @@ -130,21 +126,16 @@ export const useSwapCalculator = ( }); }, [asset]); - - useEffect(() => { processOrderBook(); }, [fromAmount]); - - const processOrderBook = () => { - const { tooMuchSlippage: _tooMuchSlippage, invalidAmount: _invalidAmount, toAmount: _toAmount } = HiveMarket.processHiveOrderBook( - buyOrderBook, - sellOrderBook, - fromAmount, - asset - ); + const { + tooMuchSlippage: _tooMuchSlippage, + invalidAmount: _invalidAmount, + toAmount: _toAmount, + } = HiveMarket.processHiveOrderBook(buyOrderBook, sellOrderBook, fromAmount, asset); setTooMuchSlippage(!!_tooMuchSlippage); setOfferUnavailable(!!_invalidAmount); if (_toAmount) { @@ -152,7 +143,6 @@ export const useSwapCalculator = ( } }; - const fetchOrderBook = async () => { setIsLoading(true); try { diff --git a/src/screens/trade/styles/assetChangeBtn.styles.ts b/src/screens/trade/styles/assetChangeBtn.styles.ts index f17dbfd2b..2c08f037e 100644 --- a/src/screens/trade/styles/assetChangeBtn.styles.ts +++ b/src/screens/trade/styles/assetChangeBtn.styles.ts @@ -2,26 +2,25 @@ import { ViewStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ - changeBtnContainer:{ - position: 'absolute', - top: 0, - bottom: 0, - right: 0, - left: 0, - justifyContent: 'center', - alignItems: 'center' - } as ViewStyle, - changeBtn: { - justifyContent:'center', - alignItems:'center', - backgroundColor: '$primaryLightBackground', - borderRadius: 28, - borderWidth: 8, - borderColor: '$primaryBackgroundColor', - } as ViewStyle, - changeBtnSize:{ - height: 60, - width: 60, - } as ViewStyle, -}) - + changeBtnContainer: { + position: 'absolute', + top: 0, + bottom: 0, + right: 0, + left: 0, + justifyContent: 'center', + alignItems: 'center', + } as ViewStyle, + changeBtn: { + justifyContent: 'center', + alignItems: 'center', + backgroundColor: '$primaryLightBackground', + borderRadius: 28, + borderWidth: 8, + borderColor: '$primaryBackgroundColor', + } as ViewStyle, + changeBtnSize: { + height: 60, + width: 60, + } as ViewStyle, +}); diff --git a/src/screens/trade/styles/errorSection.styles.ts b/src/screens/trade/styles/errorSection.styles.ts index 5779128c8..700466b1e 100644 --- a/src/screens/trade/styles/errorSection.styles.ts +++ b/src/screens/trade/styles/errorSection.styles.ts @@ -2,37 +2,37 @@ import { TextStyle, ViewStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ - container: { - margin: 12, - padding: 14, - borderRadius: 16, - flexDirection:'row', - justifyContent: 'space-between', - alignItems:'center', - backgroundColor: '$primaryRed' - } as ViewStyle, - label: { - fontSize: 14, - flex: 1, - paddingRight:12, - color: '$pureWhite', - } as TextStyle, - freeContainer:{ - paddingVertical:4, - paddingHorizontal:8, - borderRadius:6, - marginHorizontal:8, - backgroundColor:'$primaryGreen' - } as ViewStyle, - free: { - borderWidth: 0, - color: '$primaryDarkText', - fontSize: 16, - fontWeight: 'bold', - } as TextStyle, - fiat: { - fontSize: 14, - padding: 10, - color: '$iconColor' - } -}) \ No newline at end of file + container: { + margin: 12, + padding: 14, + borderRadius: 16, + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + backgroundColor: '$primaryRed', + } as ViewStyle, + label: { + fontSize: 14, + flex: 1, + paddingRight: 12, + color: '$pureWhite', + } as TextStyle, + freeContainer: { + paddingVertical: 4, + paddingHorizontal: 8, + borderRadius: 6, + marginHorizontal: 8, + backgroundColor: '$primaryGreen', + } as ViewStyle, + free: { + borderWidth: 0, + color: '$primaryDarkText', + fontSize: 16, + fontWeight: 'bold', + } as TextStyle, + fiat: { + fontSize: 14, + padding: 10, + color: '$iconColor', + }, +}); diff --git a/src/screens/trade/styles/swapAmountInput.styles.ts b/src/screens/trade/styles/swapAmountInput.styles.ts index 3aa68aebe..dedb19a98 100644 --- a/src/screens/trade/styles/swapAmountInput.styles.ts +++ b/src/screens/trade/styles/swapAmountInput.styles.ts @@ -2,51 +2,50 @@ import { TextStyle, ViewStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ - container: { - marginHorizontal: 12, - marginVertical:6, - paddingHorizontal: 16, - paddingBottom:32, - paddingTop:12, - borderWidth: 1, - borderRadius: 16, - borderColor: '$primaryLightBackground', - backgroundColor: '$primaryLightBackground' - } as ViewStyle, - label: { - fontSize: 18, - color: '$primaryDarkText', - paddingVertical: 6, - } as TextStyle, - inputContainer:{ - flexDirection:'row', - justifyContent:'space-between', - alignItems:'center', - } as ViewStyle, - input: { - flex: 1, - borderWidth: 0, - color: '$primaryDarkText', - fontSize: 28, - fontWeight: 'bold', - paddingVertical: 6, - marginTop: 10, - } as TextStyle, - symbolContainer:{ - padding:6, - paddingHorizontal:12, - backgroundColor:'$primaryDarkGray', - borderRadius:24, - } as ViewStyle, - symbol:{ - fontSize:16, - fontWeight:'bold', - color: '$white', - } as TextStyle, - fiat: { - fontSize: 14, - paddingVertical: 6, - color: '$iconColor' - }, - -}) \ No newline at end of file + container: { + marginHorizontal: 12, + marginVertical: 6, + paddingHorizontal: 16, + paddingBottom: 32, + paddingTop: 12, + borderWidth: 1, + borderRadius: 16, + borderColor: '$primaryLightBackground', + backgroundColor: '$primaryLightBackground', + } as ViewStyle, + label: { + fontSize: 18, + color: '$primaryDarkText', + paddingVertical: 6, + } as TextStyle, + inputContainer: { + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + } as ViewStyle, + input: { + flex: 1, + borderWidth: 0, + color: '$primaryDarkText', + fontSize: 28, + fontWeight: 'bold', + paddingVertical: 6, + marginTop: 10, + } as TextStyle, + symbolContainer: { + padding: 6, + paddingHorizontal: 12, + backgroundColor: '$primaryDarkGray', + borderRadius: 24, + } as ViewStyle, + symbol: { + fontSize: 16, + fontWeight: 'bold', + color: '$white', + } as TextStyle, + fiat: { + fontSize: 14, + paddingVertical: 6, + color: '$iconColor', + }, +}); diff --git a/src/screens/trade/styles/swapFeeSection.styles.ts b/src/screens/trade/styles/swapFeeSection.styles.ts index 1e3e71155..3b3a143ea 100644 --- a/src/screens/trade/styles/swapFeeSection.styles.ts +++ b/src/screens/trade/styles/swapFeeSection.styles.ts @@ -2,36 +2,36 @@ import { TextStyle, ViewStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ - container: { - margin: 12, - padding: 6, - borderRadius: 16, - flexDirection:'row', - justifyContent: 'space-between', - alignItems:'center', - backgroundColor: '$primaryLightBackground' - } as ViewStyle, - label: { - fontSize: 18, - color: '$primaryDarkText', - padding: 10, - } as TextStyle, - freeContainer:{ - paddingVertical:4, - paddingHorizontal:8, - borderRadius:6, - marginHorizontal:8, - backgroundColor:'$primaryGreen' - } as ViewStyle, - free: { - borderWidth: 0, - color: '$primaryDarkText', - fontSize: 16, - fontWeight: 'bold', - } as TextStyle, - fiat: { - fontSize: 14, - padding: 10, - color: '$iconColor' - } -}) \ No newline at end of file + container: { + margin: 12, + padding: 6, + borderRadius: 16, + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + backgroundColor: '$primaryLightBackground', + } as ViewStyle, + label: { + fontSize: 18, + color: '$primaryDarkText', + padding: 10, + } as TextStyle, + freeContainer: { + paddingVertical: 4, + paddingHorizontal: 8, + borderRadius: 6, + marginHorizontal: 8, + backgroundColor: '$primaryGreen', + } as ViewStyle, + free: { + borderWidth: 0, + color: '$primaryDarkText', + fontSize: 16, + fontWeight: 'bold', + } as TextStyle, + fiat: { + fontSize: 14, + padding: 10, + color: '$iconColor', + }, +}); diff --git a/src/screens/trade/styles/tradeScreen.styles.ts b/src/screens/trade/styles/tradeScreen.styles.ts index add883168..d63b14fd8 100644 --- a/src/screens/trade/styles/tradeScreen.styles.ts +++ b/src/screens/trade/styles/tradeScreen.styles.ts @@ -4,24 +4,24 @@ import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ container: { flex: 1, - backgroundColor: '$primaryBackgroundColor' + backgroundColor: '$primaryBackgroundColor', }, balance: { marginHorizontal: 16, fontSize: 14, color: '$iconColor', - alignSelf: 'flex-end' + alignSelf: 'flex-end', } as TextStyle, marketRate: { padding: 10, marginHorizontal: 10, fontSize: 16, fontWeight: 'bold', - color: '$primaryDarkText' + color: '$primaryDarkText', } as TextStyle, - mainBtnContainer:{ - alignItems:'center' + mainBtnContainer: { + alignItems: 'center', } as ViewStyle, mainBtn: { width: '$deviceWidth / 3', @@ -30,7 +30,7 @@ export default EStyleSheet.create({ fontWeight: 'bold', marginVertical: 16, } as ViewStyle, - buttonText:{ + buttonText: { color: 'white', - } -}) \ No newline at end of file + }, +}); diff --git a/src/screens/voters/screen/votersScreen.js b/src/screens/voters/screen/votersScreen.js index 6013ee996..35e06ea4c 100644 --- a/src/screens/voters/screen/votersScreen.js +++ b/src/screens/voters/screen/votersScreen.js @@ -25,20 +25,18 @@ const VotersScreen = ({ route }) => { id: 'voters.voters_info', }); - useEffect(() => { if (route.params?.content) { getActiveVotes(get(post, 'author'), get(post, 'permlink')) .then((result) => { result.sort((a, b) => b.rshares - a.rshares); - post.active_votes = parseActiveVotes({ ...post, active_votes: result });; - setPost({...post}); + post.active_votes = parseActiveVotes({ ...post, active_votes: result }); + setPost({ ...post }); }) .catch(() => {}); } }, [route.params?.content]); - const _activeVotes = _cPost.active_votes.slice(); return ( diff --git a/src/screens/wallet/screen/walletScreen.tsx b/src/screens/wallet/screen/walletScreen.tsx index c38332dc1..d2f58e039 100644 --- a/src/screens/wallet/screen/walletScreen.tsx +++ b/src/screens/wallet/screen/walletScreen.tsx @@ -4,7 +4,7 @@ import { SafeAreaView, View, Text, AppState, AppStateStatus } from 'react-native import { isArray } from 'lodash'; // Containers -import {RefreshControl, FlatList, gestureHandlerRootHOC } from 'react-native-gesture-handler'; +import { RefreshControl, FlatList, gestureHandlerRootHOC } from 'react-native-gesture-handler'; import { useIntl } from 'react-intl'; import moment from 'moment'; import { LoggedInContainer } from '../../../containers'; @@ -39,10 +39,10 @@ const WalletScreen = ({ navigation }) => { const intl = useIntl(); const dispatch = useAppDispatch(); - //refs + // refs const appState = useRef(AppState.currentState); - //redux + // redux const isDarkTheme = useAppSelector((state) => state.application.isDarkTheme); const currency = useAppSelector((state) => state.application.currency); @@ -51,15 +51,15 @@ const WalletScreen = ({ navigation }) => { const currentAccount = useAppSelector((state) => state.account.currentAccount); - //queries + // queries const walletQuery = walletQueries.useAssetsQuery(); const unclaimedRewardsQuery = walletQueries.useUnclaimedRewardsQuery(); const claimRewardsMutation = walletQueries.useClaimRewardsMutation(); - //state + // state const [isRefreshing, setIsRefreshing] = useState(false); - //side-effects + // side-effects useEffect(() => { const appStateSub = AppState.addEventListener('change', _handleAppStateChange); @@ -84,9 +84,9 @@ const WalletScreen = ({ navigation }) => { _fetchPriceHistory(); }, [selectedCoins]); - //actions + // actions const populateSelectedAssets = (tokensArr) => { - return tokensArr.map(({symbol, type}) => ({ + return tokensArr.map(({ symbol, type }) => ({ id: symbol, symbol, isEngine: type === 'ENGINE', @@ -101,15 +101,12 @@ const WalletScreen = ({ navigation }) => { ); if (isArray(currentAccount.about?.profile?.tokens)) { - const _selectedAssets = populateSelectedAssets( - currentAccount.about.profile.tokens, - ); + const _selectedAssets = populateSelectedAssets(currentAccount.about.profile.tokens); // check if current selected engine tokens differ from profile json meta if (JSON.stringify(_selectedAssets) !== JSON.stringify(currSelectedEngineTokens)) { dispatch(setSelectedCoins([...DEFAULT_ASSETS, ..._selectedAssets])); } } - }; const _handleAppStateChange = (nextAppState: AppStateStatus) => { @@ -132,22 +129,15 @@ const WalletScreen = ({ navigation }) => { const curTime = new Date().getTime(); if (!token.notCrypto && curTime > expiresAt) { - let priceData: number[] = []; if (token.isEngine) { const marketData = await fetchEngineMarketData(token.id); priceData = marketData.map((data) => data.close); - - } else if(token.isSpk){ - //TODO: add request to fetch chart data if available - + } else if (token.isSpk) { + // TODO: add request to fetch chart data if available } else { - const marketChart = await fetchMarketChart( - token.id, - currency.currency, - CHART_DAYS_RANGE, - ); + const marketChart = await fetchMarketChart(token.id, currency.currency, CHART_DAYS_RANGE); priceData = marketChart.prices.map((item) => item.yValue); } @@ -166,15 +156,14 @@ const WalletScreen = ({ navigation }) => { }; const _claimRewards = (assetId: string) => { - //claim using mutation; + // claim using mutation; claimRewardsMutation.mutate({ assetId }); }; const _showAssetsSelectModal = () => { - navigation.navigate(ROUTES.MODALS.ASSETS_SELECT) + navigation.navigate(ROUTES.MODALS.ASSETS_SELECT); }; - const _renderItem = ({ item, index }: { item: CoinBase; index: number }) => { const coinData: CoinData = coinsData[item.id]; const unclaimedRewards = diff --git a/src/screens/wallet/styles/children.styles.ts b/src/screens/wallet/styles/children.styles.ts index 2e06b8499..a0e4b96e2 100644 --- a/src/screens/wallet/styles/children.styles.ts +++ b/src/screens/wallet/styles/children.styles.ts @@ -27,13 +27,13 @@ export default EStyleSheet.create({ } as ViewStyle, cardValuesContainer: { - flex:1, + flex: 1, marginHorizontal: 8, justifyContent: 'flex-end', } as ViewStyle, logoContainer: { - paddingRight: 8 + paddingRight: 8, } as ImageStyle, menuIcon: { @@ -48,13 +48,13 @@ export default EStyleSheet.create({ backgroundColor: '$darkGrayBackground', }, - claimContainer:{ - marginTop:16, + claimContainer: { + marginTop: 16, }, chartContainer: { - height:80, - marginTop:-16, + height: 80, + marginTop: -16, }, cardFooter: { position: 'absolute', diff --git a/src/screens/wallet/styles/claimButton.styles.ts b/src/screens/wallet/styles/claimButton.styles.ts index 1d2a7f126..315b4cb56 100644 --- a/src/screens/wallet/styles/claimButton.styles.ts +++ b/src/screens/wallet/styles/claimButton.styles.ts @@ -2,7 +2,7 @@ import { TextStyle, ViewStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ - engineBtnContainer: { + engineBtnContainer: { alignItems: 'flex-end', marginHorizontal: 32, marginVertical: 8, @@ -10,10 +10,10 @@ export default EStyleSheet.create({ engineBtnText: { color: '$primaryBlue', } as TextStyle, - engineHeaderContainer:{ - flexDirection:'row-reverse', - justifyContent:'space-between', - alignItems:'center' + engineHeaderContainer: { + flexDirection: 'row-reverse', + justifyContent: 'space-between', + alignItems: 'center', } as ViewStyle, claimActivityIndicator: { marginLeft: 16, @@ -47,4 +47,4 @@ export default EStyleSheet.create({ alignSelf: 'center', textTransform: 'uppercase', } as TextStyle, -}) \ No newline at end of file +}); diff --git a/src/screens/wallet/styles/manageAssets.styles.ts b/src/screens/wallet/styles/manageAssets.styles.ts index 92c75609e..ed963c1ba 100644 --- a/src/screens/wallet/styles/manageAssets.styles.ts +++ b/src/screens/wallet/styles/manageAssets.styles.ts @@ -2,12 +2,13 @@ import { TextStyle, ViewStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ - container:{ - marginBottom:12, marginTop:8, + container: { + marginBottom: 12, + marginTop: 8, marginHorizontal: 16, - borderRadius:12, - borderWidth:4, - borderColor:'$primaryLightBackground' + borderRadius: 12, + borderWidth: 4, + borderColor: '$primaryLightBackground', } as ViewStyle, engineBtnContainer: { alignItems: 'flex-end', @@ -20,23 +21,21 @@ export default EStyleSheet.create({ marginHorizontal: 16, flexDirection: 'row', justifyContent: 'center', - alignItems: 'center' + alignItems: 'center', } as ViewStyle, - title:{ - fontSize:16, - color: '$primaryBlack' + title: { + fontSize: 16, + color: '$primaryBlack', } as TextStyle, rightIconWrapper: { alignSelf: 'center', width: 40, - height:40, - borderRadius:20, - + height: 40, + borderRadius: 20, } as ViewStyle, rightIcon: { color: '$primaryBlack', marginVertical: 12, marginHorizontal: 8, - } as ViewStyle, -}) \ No newline at end of file +}); diff --git a/src/screens/waves/children/wavesHeader.tsx b/src/screens/waves/children/wavesHeader.tsx index 67367826a..aa25556f4 100644 --- a/src/screens/waves/children/wavesHeader.tsx +++ b/src/screens/waves/children/wavesHeader.tsx @@ -1,32 +1,27 @@ import React from 'react'; import { View, Text } from 'react-native'; +import { useDispatch } from 'react-redux'; +import { useIntl } from 'react-intl'; import { WritePostButton } from '../../../components/atoms'; import { showReplyModal } from '../../../redux/actions/uiAction'; -import { useDispatch } from 'react-redux'; import styles from '../styles/children.styles'; -import { useIntl } from 'react-intl'; -interface WavesHeaderProps { - -} - -export const WavesHeader: React.FC = ({ }) => { +interface WavesHeaderProps {} +export const WavesHeader: React.FC = ({}) => { const dispatch = useDispatch(); const intl = useIntl(); const _onPress = () => { - dispatch(showReplyModal({mode:'wave'})); - } + dispatch(showReplyModal({ mode: 'wave' })); + }; return ( - {intl.formatMessage({id:'post.ecency_waves'})} - + {intl.formatMessage({ id: 'post.ecency_waves' })} + - ); }; - -export default WavesHeader; \ No newline at end of file +export default WavesHeader; diff --git a/src/screens/waves/screen/wavesScreen.tsx b/src/screens/waves/screen/wavesScreen.tsx index 86444ef8b..a78e0b643 100644 --- a/src/screens/waves/screen/wavesScreen.tsx +++ b/src/screens/waves/screen/wavesScreen.tsx @@ -1,5 +1,15 @@ import React, { useEffect, useRef, useState } from 'react'; -import { ActivityIndicator, NativeScrollEvent, NativeSyntheticEvent, RefreshControl, View, FlatList, AppState } from 'react-native'; +import { + ActivityIndicator, + NativeScrollEvent, + NativeSyntheticEvent, + RefreshControl, + View, + FlatList, + AppState, +} from 'react-native'; +import { debounce } from 'lodash'; +import { useNavigationState } from '@react-navigation/native'; import { Comments, EmptyScreen, Header, PostOptionsModal } from '../../../components'; import styles from '../styles/wavesScreen.styles'; import { wavesQueries } from '../../../providers/queries'; @@ -7,179 +17,160 @@ import { useAppSelector } from '../../../hooks'; import WavesHeader from '../children/wavesHeader'; import { PostTypes } from '../../../constants/postTypes'; import ScrollTopPopup from '../../../components/tabbedPosts/view/scrollTopPopup'; -import { debounce } from 'lodash'; -import { useNavigationState } from '@react-navigation/native'; - const SCROLL_POPUP_THRESHOLD = 5000; - const WavesScreen = ({ route }) => { - //refs - const postOptionsModalRef = useRef(null); - const postsListRef = useRef(); - const blockPopupRef = useRef(false); - const scrollOffsetRef = useRef(0); - const appState = useRef(AppState.currentState); - const isFirstRender = useRef(true); + // refs + const postOptionsModalRef = useRef(null); + const postsListRef = useRef(); + const blockPopupRef = useRef(false); + const scrollOffsetRef = useRef(0); + const appState = useRef(AppState.currentState); + const isFirstRender = useRef(true); - const wavesQuery = wavesQueries.useWavesQuery('ecency.waves'); + const wavesQuery = wavesQueries.useWavesQuery('ecency.waves'); - const isDarkTheme = useAppSelector(state => state.application.isDarkTheme) + const isDarkTheme = useAppSelector((state) => state.application.isDarkTheme); - const navState = useNavigationState(state => state); + const navState = useNavigationState((state) => state); - const [enableScrollTop, setEnableScrollTop] = useState(false); - const [popupAvatars, setPopupAvatars] = useState([]) + const [enableScrollTop, setEnableScrollTop] = useState(false); + const [popupAvatars, setPopupAvatars] = useState([]); - - - useEffect(() => { - - const _stateSub = AppState.addEventListener('change', _handleAppStateChange); - return () => { - _stateSub.remove(); - } - }, []) - - - useEffect(() => { - if (navState.routeNames[navState.index] === route.name && !isFirstRender.current) { - _latestWavesCheck(); - } - isFirstRender.current = false; - }, [navState.index]) - - - - //actions - const _handleAppStateChange = async (nextAppState) => { - - if ( - appState.current.match(/inactive|background/) && - nextAppState === 'active' - ) { - _latestWavesCheck() - } - - appState.current = nextAppState; + useEffect(() => { + const _stateSub = AppState.addEventListener('change', _handleAppStateChange); + return () => { + _stateSub.remove(); }; + }, []); + useEffect(() => { + if (navState.routeNames[navState.index] === route.name && !isFirstRender.current) { + _latestWavesCheck(); + } + isFirstRender.current = false; + }, [navState.index]); - const _latestWavesCheck = async () => { - const latestWaves = await wavesQuery.latestWavesFetch() - if (latestWaves.length > 0) { - setPopupAvatars(latestWaves.map((item) => item.avatar)) - setEnableScrollTop(true) - } + // actions + const _handleAppStateChange = async (nextAppState) => { + if (appState.current.match(/inactive|background/) && nextAppState === 'active') { + _latestWavesCheck(); } - const _fetchData = (fetchProps: any) => { - if (fetchProps?.refresh) { - wavesQuery.refresh(); - } else { - wavesQuery.fetchNextPage(); - } - } + appState.current = nextAppState; + }; - //scrolls to top, blocks scroll popup for 2 seconds to reappear after scroll - const _scrollTop = () => { - if (postsListRef.current) { - postsListRef.current.scrollToOffset({ offset: 0 }); + const _latestWavesCheck = async () => { + const latestWaves = await wavesQuery.latestWavesFetch(); + if (latestWaves.length > 0) { + setPopupAvatars(latestWaves.map((item) => item.avatar)); + setEnableScrollTop(true); + } + }; + + const _fetchData = (fetchProps: any) => { + if (fetchProps?.refresh) { + wavesQuery.refresh(); + } else { + wavesQuery.fetchNextPage(); + } + }; + + // scrolls to top, blocks scroll popup for 2 seconds to reappear after scroll + const _scrollTop = () => { + if (postsListRef.current) { + postsListRef.current.scrollToOffset({ offset: 0 }); + setEnableScrollTop(false); + setPopupAvatars([]); + scrollPopupDebouce.cancel(); + blockPopupRef.current = true; + setTimeout(() => { + blockPopupRef.current = false; + }, 2000); + } + }; + + // makes sure pop do not reappear while scrolling up + const scrollPopupDebouce = debounce( + (value) => { + setEnableScrollTop(value); + }, + 500, + { leading: true }, + ); + + // calback to calculate with to display scroll to popup + const _onScroll = (event: NativeSyntheticEvent) => { + const currentOffset = event.nativeEvent.contentOffset.y; + const scrollUp = currentOffset < scrollOffsetRef.current; + scrollOffsetRef.current = currentOffset; + + if (scrollUp && !blockPopupRef.current && currentOffset > SCROLL_POPUP_THRESHOLD) { + scrollPopupDebouce(true); + } + }; + + const _handleOnOptionsPress = (content: any) => { + if (postOptionsModalRef.current) { + postOptionsModalRef.current.show(content); + } + }; + + const _data = wavesQuery.data; + + const _renderListHeader = ; + const _renderListFooter = () => + wavesQuery.isLoading && !wavesQuery.isRefreshing ? ( + + ) : ( + + ); + const _renderListEmpty = () => + wavesQuery.isRefreshing || wavesQuery.isLoading ? : ; + + return ( + +
+ + + _fetchData({ refresh: true })} + progressBackgroundColor="#357CE6" + tintColor={!isDarkTheme ? '#357ce6' : '#96c0ff'} + titleColor="#fff" + colors={['#fff']} + /> + ), + }} + /> + { setEnableScrollTop(false); - setPopupAvatars([]) - scrollPopupDebouce.cancel(); - blockPopupRef.current = true; - setTimeout(() => { - blockPopupRef.current = false; - }, 2000); - } - } + setPopupAvatars([]); + }} + /> + - //makes sure pop do not reappear while scrolling up - const scrollPopupDebouce = debounce( - (value) => { - setEnableScrollTop(value); - }, - 500, - { leading: true }, - ); - - //calback to calculate with to display scroll to popup - const _onScroll = (event: NativeSyntheticEvent) => { - let currentOffset = event.nativeEvent.contentOffset.y; - let scrollUp = currentOffset < scrollOffsetRef.current; - scrollOffsetRef.current = currentOffset; - - if (scrollUp && !blockPopupRef.current && currentOffset > SCROLL_POPUP_THRESHOLD) { - scrollPopupDebouce(true); - } - }; - - - - const _handleOnOptionsPress = (content: any) => { - if (postOptionsModalRef.current) { - postOptionsModalRef.current.show(content); - } - } - - const _data = wavesQuery.data; - - const _renderListHeader = ( - - ) - const _renderListFooter = () => wavesQuery.isLoading && !wavesQuery.isRefreshing - ? : ; - const _renderListEmpty = () => wavesQuery.isRefreshing || wavesQuery.isLoading - ? : ; - - return ( - -
- - - _fetchData({ refresh: true })} - progressBackgroundColor="#357CE6" - tintColor={!isDarkTheme ? '#357ce6' : '#96c0ff'} - titleColor="#fff" - colors={['#fff']} - /> - ), - }} - /> - { - setEnableScrollTop(false); - setPopupAvatars([]) - }} - /> - - - - - - - - ); + + + ); }; - -export default WavesScreen; \ No newline at end of file +export default WavesScreen; diff --git a/src/screens/waves/styles/children.styles.ts b/src/screens/waves/styles/children.styles.ts index f4c984ae4..0a93a30c4 100644 --- a/src/screens/waves/styles/children.styles.ts +++ b/src/screens/waves/styles/children.styles.ts @@ -3,16 +3,16 @@ import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ headerContainer: { - paddingHorizontal:12, - paddingBottom:6, - marginBottom:4, - borderBottomWidth:1, - borderColor:'$primaryLightBackground' + paddingHorizontal: 12, + paddingBottom: 6, + marginBottom: 4, + borderBottomWidth: 1, + borderColor: '$primaryLightBackground', } as ViewStyle, - headerTitle:{ - color:'$primaryDarkText', - marginTop:16, - fontSize:24, - fontWeight:'200' - } as TextStyle + headerTitle: { + color: '$primaryDarkText', + marginTop: 16, + fontSize: 24, + fontWeight: '200', + } as TextStyle, }); diff --git a/src/screens/waves/styles/wavesScreen.styles.ts b/src/screens/waves/styles/wavesScreen.styles.ts index d6d415ea7..958f49779 100644 --- a/src/screens/waves/styles/wavesScreen.styles.ts +++ b/src/screens/waves/styles/wavesScreen.styles.ts @@ -3,9 +3,7 @@ import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ container: { - flex:1, + flex: 1, backgroundColor: '$primaryBackgroundColor', - } as ViewStyle, - -}) \ No newline at end of file +}); diff --git a/src/utils/filterNsfwPost.js b/src/utils/filterNsfwPost.js index 2902f596c..0f77dbc2d 100644 --- a/src/utils/filterNsfwPost.js +++ b/src/utils/filterNsfwPost.js @@ -9,7 +9,10 @@ export default (posts, option) => { case '1': posts.map((post) => { - if (post.parent_permlink === 'nsfw' || get(post, 'json_metadata.tags', []).includes('nsfw')) { + if ( + post.parent_permlink === 'nsfw' || + get(post, 'json_metadata.tags', []).includes('nsfw') + ) { post.nsfw = true; } }); @@ -25,7 +28,6 @@ export default (posts, option) => { } }); return updatedPosts; - } }; /* eslint-enable */ diff --git a/src/utils/hive-uri.ts b/src/utils/hive-uri.ts index 7911cf828..74c812ec5 100644 --- a/src/utils/hive-uri.ts +++ b/src/utils/hive-uri.ts @@ -1,4 +1,5 @@ import { get, isArray } from 'lodash'; + const operationsData = require('./operations.json'); /** @@ -8,7 +9,7 @@ const operationsData = require('./operations.json'); * */ export const isHiveUri = (uri: string) => { - let trimUri = uri.trim(); + const trimUri = uri.trim(); return trimUri.startsWith('hive://'); }; @@ -18,7 +19,7 @@ const _checkOpsArray = (ops: any) => { }; const findParentKey = (obj, value, parentKey = null) => { - for (let key in obj) { + for (const key in obj) { if (obj[key] === value) { return parentKey; } else if (typeof obj[key] === 'object') { @@ -68,7 +69,7 @@ const _formatAmount = (amount: string) => { * */ export const getFormattedTx = (tx: any, authoritiesMap: Map) => { let opName; - let errorObj = { + const errorObj = { errorKey1: '', errorKey2: '', authorityKeyType: '', @@ -83,7 +84,7 @@ export const getFormattedTx = (tx: any, authoritiesMap: Map) => } const op = ops[0]; // single operation const operationName = op[0]; // operation name - let operationObj = op[1]; // operation object + const operationObj = op[1]; // operation object if (!operationName) { errorObj.errorKey1 = 'qr.invalid_op'; @@ -125,5 +126,5 @@ export const getFormattedTx = (tx: any, authoritiesMap: Map) => operations: [[operationName, operationObj]], }; // resolve with formatted tx and opName - return Promise.resolve({ tx: tx, opName: opName }); + return Promise.resolve({ tx, opName }); }; diff --git a/src/utils/migrationHelpers.ts b/src/utils/migrationHelpers.ts index ab2b0d6fd..4264b34ef 100644 --- a/src/utils/migrationHelpers.ts +++ b/src/utils/migrationHelpers.ts @@ -294,7 +294,7 @@ const reduxMigrations = { 6: (state) => { state.application.waveUpvotePercent = state.application.commentUpvotePercent; return state; - } + }, }; export default { diff --git a/src/utils/number.ts b/src/utils/number.ts index 156229c6f..97c3a9f36 100644 --- a/src/utils/number.ts +++ b/src/utils/number.ts @@ -10,7 +10,7 @@ export const countDecimals = (value) => { return value.toString().split('.')[1].length || 0; }; -export const stripDecimalPlaces = (value: number, precision: number = 3) => { +export const stripDecimalPlaces = (value: number, precision = 3) => { if (!Number(value)) { return 0; } @@ -26,11 +26,11 @@ export const getDecimalPlaces = (value: number) => { return match ? match[0].length : 0; }; -export const formatNumberInputStr = (text: string, precision: number = 10) => { +export const formatNumberInputStr = (text: string, precision = 10) => { if (text.includes(',')) { text = text.replace(',', '.'); } - + const _num = parseFloat(text); if (_num) { diff --git a/src/utils/postParser.tsx b/src/utils/postParser.tsx index 7d277ef2e..d8b106c69 100644 --- a/src/utils/postParser.tsx +++ b/src/utils/postParser.tsx @@ -111,8 +111,7 @@ export const parseDiscussionCollection = async (commentsMap: { [key: string]: an return commentsMap; }; - -//TODO: discard/deprecate method after porting getComments in commentsContainer to getDiscussionCollection +// TODO: discard/deprecate method after porting getComments in commentsContainer to getDiscussionCollection export const parseCommentThreads = async (commentsMap: any, author: string, permlink: string) => { const MAX_THREAD_LEVEL = 3; const comments = []; @@ -154,8 +153,12 @@ export const parseCommentThreads = async (commentsMap: any, author: string, perm return comments; }; - -export const mapDiscussionToThreads = async (commentsMap: any, author: string, permlink: string, maxLevel: number = 3) => { +export const mapDiscussionToThreads = async ( + commentsMap: any, + author: string, + permlink: string, + maxLevel = 3, +) => { const comments = []; if (!commentsMap) { @@ -184,7 +187,6 @@ export const mapDiscussionToThreads = async (commentsMap: any, author: string, p // prcoess first level comment if (comment && comment.parent_author === author && comment.parent_permlink === permlink) { - comment.replies = parseReplies(commentsMap, comment.replies, 1); comments.push(comment); } @@ -194,7 +196,6 @@ export const mapDiscussionToThreads = async (commentsMap: any, author: string, p return comments; }; - export const parseComments = (comments: any[]) => { if (!comments) { return null; @@ -246,7 +247,6 @@ export const parseComment = (comment: any) => { return comment; }; - export const injectPostCache = (commentsMap, cachedComments, cachedVotes, lastCacheUpdate) => { let shouldClone = false; const _comments = commentsMap || {}; @@ -301,10 +301,7 @@ export const injectPostCache = (commentsMap, cachedComments, cachedVotes, lastCa _comments[_parentPath].children = _comments[_parentPath].children + 1; // if comment was created very recently enable auto reveal - if ( - lastCacheUpdate.postPath === path && - currentTime - lastCacheUpdate.updatedAt < 5000 - ) { + if (lastCacheUpdate.postPath === path && currentTime - lastCacheUpdate.updatedAt < 5000) { console.log('setting show replies flag'); _comments[_parentPath].expandedReplies = true; _comments[path].renderOnTop = true; @@ -315,42 +312,39 @@ export const injectPostCache = (commentsMap, cachedComments, cachedVotes, lastCa } return shouldClone ? { ..._comments } : _comments; -} - +}; export const injectVoteCache = (post, voteCache) => { if (voteCache && voteCache.status !== CacheStatus.FAILED) { - const _voteIndex = post.active_votes.findIndex((i) => i.voter === voteCache.voter); - //if vote do not already exist + // if vote do not already exist if (_voteIndex < 0 && voteCache.status !== CacheStatus.DELETED) { - post.total_payout += voteCache.amount * (voteCache.isDownvote ? -1 : 1); - //calculate updated totalRShares and send to post + // calculate updated totalRShares and send to post const _totalRShares = post.active_votes.reduce( (accumulator: number, item: any) => accumulator + parseFloat(item.rshares), - voteCache.rshares); + voteCache.rshares, + ); const _newVote = parseVote(voteCache, post, _totalRShares); post.active_votes = [...post.active_votes, _newVote]; } - //if vote already exist + // if vote already exist else { - const _vote = post.active_votes[_voteIndex]; - //get older and new reward for the vote + // get older and new reward for the vote const _oldReward = calculateVoteReward(_vote.rshares, post); - //update total payout + // update total payout const _voteAmount = voteCache.amount * (voteCache.isDownvote ? -1 : 1); - post.total_payout += _voteAmount - _oldReward + post.total_payout += _voteAmount - _oldReward; - //update vote entry - _vote.rshares = voteCache.rshares - _vote.percent100 = _vote.percent && voteCache.percent / 100 + // update vote entry + _vote.rshares = voteCache.rshares; + _vote.percent100 = _vote.percent && voteCache.percent / 100; post.active_votes[_voteIndex] = _vote; post.active_votes = [...post.active_votes]; @@ -360,7 +354,6 @@ export const injectVoteCache = (post, voteCache) => { return post; }; - export const isVoted = async (activeVotes, currentUserName) => { if (!currentUserName) { return false; @@ -374,8 +367,6 @@ export const isVoted = async (activeVotes, currentUserName) => { return false; }; - - export const isDownVoted = async (activeVotes, currentUserName) => { if (!currentUserName) { return false; @@ -389,20 +380,16 @@ export const isDownVoted = async (activeVotes, currentUserName) => { return false; }; - - export const parseActiveVotes = (post) => { - const _totalRShares = post.active_votes.reduce((a, b) => a + parseFloat(b.rshares), 0); if (isArray(post.active_votes)) { - post.active_votes = post.active_votes.map((vote) => parseVote(vote, post, _totalRShares)) + post.active_votes = post.active_votes.map((vote) => parseVote(vote, post, _totalRShares)); } return post.active_votes; }; - export const parseVote = (activeVote: any, post: any, _totalRShares?: number) => { activeVote.reward = calculateVoteReward(activeVote.rshares, post, _totalRShares).toFixed(3); activeVote.percent100 = activeVote.percent / 100; @@ -410,7 +397,7 @@ export const parseVote = (activeVote: any, post: any, _totalRShares?: number) => activeVote.avatar = getResizedAvatar(activeVote.voter); return activeVote; -} +}; const parseTags = (post: any) => { if (post.json_metadata) { diff --git a/src/utils/time.js b/src/utils/time.js index b43f9cc19..876ce9dba 100644 --- a/src/utils/time.js +++ b/src/utils/time.js @@ -159,14 +159,14 @@ export const dateToFormatted = (d, format = 'LLLL') => { /** * calculates hours difference between two dates, negative value will mean first date * is from past time - * @param {Base date from whcich date2 will be subtracted} date1 - * @param {Date to be subtracted} date2 + * @param {Base date from whcich date2 will be subtracted} date1 + * @param {Date to be subtracted} date2 * @returns number of hours difference between two dates */ export const getHoursDifferntial = (date1, date2) => { if (date1 instanceof Date && date2 instanceof Date) { - return (date1 - date2) / (60 * 60 * 1000) + return (date1 - date2) / (60 * 60 * 1000); } return 0; -} +}; diff --git a/src/utils/vote.ts b/src/utils/vote.ts index 9ed55ed5f..63d594fdf 100644 --- a/src/utils/vote.ts +++ b/src/utils/vote.ts @@ -2,33 +2,28 @@ import parseToken from './parseToken'; import { GlobalProps } from '../redux/reducers/accountReducer'; import { votingPower } from '../providers/hive/dhive'; - -export const getEstimatedAmount = (account, globalProps: GlobalProps, sliderValue: number = 1) => { +export const getEstimatedAmount = (account, globalProps: GlobalProps, sliderValue = 1) => { const { fundRecentClaims, fundRewardBalance, base, quote } = globalProps; const hbdMedian = base / quote; const weight = sliderValue * 10000; - const voteEffectiveShares = calculateEstimatedRShares(account, weight) + const voteEffectiveShares = calculateEstimatedRShares(account, weight); const voteValue = (voteEffectiveShares / fundRecentClaims) * fundRewardBalance * hbdMedian; const estimatedAmount = weight < 0 ? Math.min(voteValue * -1, 0) : Math.max(voteValue, 0); if (isNaN(estimatedAmount)) { return '0.00'; - } - else if (estimatedAmount >= 1) { - return estimatedAmount.toFixed(2) + } else if (estimatedAmount >= 1) { + return estimatedAmount.toFixed(2); } else { const _fixed = parseFloat(estimatedAmount.toFixed(4)); - const _precision = _fixed < 0.001 ? 1 : 2 + const _precision = _fixed < 0.001 ? 1 : 2; return _fixed.toPrecision(_precision); } - }; - -export const calculateEstimatedRShares = (account:any, weight: number = 10000) => { - +export const calculateEstimatedRShares = (account: any, weight = 10000) => { const _votingPower: number = votingPower(account) * 100; const vestingShares = parseToken(account.vesting_shares); const receievedVestingShares = parseToken(account.received_vesting_shares); @@ -36,9 +31,7 @@ export const calculateEstimatedRShares = (account:any, weight: number = 10000) = const totalVests = vestingShares + receievedVestingShares - delegatedVestingShared; return calculateVoteRshares(totalVests, _votingPower, weight); -} - - +}; /* * Changes in HF25 @@ -55,29 +48,28 @@ export const calculateVoteRshares = (userEffectiveVests: number, vp = 10000, wei return voteRshares; }; - - - -export const calculateVoteReward = (voteRShares:number, post:any, totalRshares?:number) => { - - if(!voteRShares){ - return 0 +export const calculateVoteReward = (voteRShares: number, post: any, totalRshares?: number) => { + if (!voteRShares) { + return 0; } const totalPayout = post.total_payout || - parseFloat(post.pending_payout_value) || 0+ - parseFloat(post.total_payout_value) || 0 + - parseFloat(post.curator_payout_value) || 0; - - if(totalRshares === undefined){ - totalRshares = post.active_votes.length - ? post.active_votes.reduce((accumulator:number, item:any) => accumulator + parseFloat(item.rshares), 0) - : voteRShares; + parseFloat(post.pending_payout_value) || + 0 + parseFloat(post.total_payout_value) || + 0 + parseFloat(post.curator_payout_value) || + 0; + if (totalRshares === undefined) { + totalRshares = post.active_votes.length + ? post.active_votes.reduce( + (accumulator: number, item: any) => accumulator + parseFloat(item.rshares), + 0, + ) + : voteRShares; } const ratio = totalPayout / totalRshares || 0; return voteRShares * ratio; -} \ No newline at end of file +}; diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index c079da6d2..0470287d3 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -33,13 +33,16 @@ import { fetchEngineAccountHistory, fetchHiveEngineTokenBalances, } from '../providers/hive-engine/hiveEngine'; -import { EngineActions, EngineOperations, HistoryItem } from '../providers/hive-engine/hiveEngine.types'; +import { + EngineActions, + EngineOperations, + HistoryItem, +} from '../providers/hive-engine/hiveEngine.types'; import { ClaimsCollection } from '../redux/reducers/cacheReducer'; import { fetchSpkWallet } from '../providers/hive-spk/hiveSpk'; import TransferTypes from '../constants/transferTypes'; import { getHoursDifferntial } from './time'; - export const transferTypes = [ 'curation_reward', 'author_reward', @@ -69,14 +72,14 @@ const HIVE_ACTIONS = [ 'transfer_to_vesting', 'withdraw_hive', 'swap_token', - TransferTypes.RECURRENT_TRANSFER + TransferTypes.RECURRENT_TRANSFER, ]; const HBD_ACTIONS = [ 'transfer_token', 'transfer_to_savings', 'convert', 'withdraw_hbd', - 'swap_token' + 'swap_token', ]; const HIVE_POWER_ACTIONS = ['delegate', 'power_down']; @@ -97,7 +100,7 @@ export const groomingTransactionData = (transaction, hivePerMVests): CoinActivit result.created = timestamp; result.icon = 'local-activity'; - //TODO: Format other wallet related operations + // TODO: Format other wallet related operations switch (result.textKey) { case 'curation_reward': @@ -125,8 +128,9 @@ export const groomingTransactionData = (transaction, hivePerMVests): CoinActivit .toFixed(3) .replace(',', '.'); - result.value = `${hbdPayout > 0 ? `${hbdPayout} HBD` : ''} ${hivePayout > 0 ? `${hivePayout} HIVE` : '' - } ${vestingPayout > 0 ? `${vestingPayout} HP` : ''}`; + result.value = `${hbdPayout > 0 ? `${hbdPayout} HBD` : ''} ${ + hivePayout > 0 ? `${hivePayout} HIVE` : '' + } ${vestingPayout > 0 ? `${vestingPayout} HP` : ''}`; result.details = author && permlink ? `@${author}/${permlink}` : null; if (result.textKey === 'comment_benefactor_reward') { @@ -140,8 +144,9 @@ export const groomingTransactionData = (transaction, hivePerMVests): CoinActivit rewardHive = parseToken(rewardHive).toFixed(3).replace(',', '.'); rewardVests = vestsToHp(parseToken(rewardVests), hivePerMVests).toFixed(3).replace(',', '.'); - result.value = `${rewardHdb > 0 ? `${rewardHdb} HBD` : ''} ${rewardHive > 0 ? `${rewardHive} HIVE` : '' - } ${rewardVests > 0 ? `${rewardVests} HP` : ''}`; + result.value = `${rewardHdb > 0 ? `${rewardHdb} HBD` : ''} ${ + rewardHive > 0 ? `${rewardHive} HIVE` : '' + } ${rewardVests > 0 ? `${rewardVests} HP` : ''}`; break; case 'transfer': case 'transfer_to_savings': @@ -174,8 +179,8 @@ export const groomingTransactionData = (transaction, hivePerMVests): CoinActivit case 'escrow_release': case 'escrow_approve': const { agent, escrow_id } = opData; - let { from: frome } = opData; - let { to: toe } = opData; + const { from: frome } = opData; + const { to: toe } = opData; result.value = `${escrow_id}`; result.icon = 'wb-iridescent'; @@ -190,28 +195,28 @@ export const groomingTransactionData = (transaction, hivePerMVests): CoinActivit result.details = delegatee && delegator ? `@${delegator} to @${delegatee}` : null; break; case 'cancel_transfer_from_savings': - let { from: from_who, request_id: requestId } = opData; + const { from: from_who, request_id: requestId } = opData; result.value = `${0}`; result.icon = 'cancel'; result.details = from_who ? `from @${from_who}, id: ${requestId}` : null; break; case 'fill_convert_request': - let { owner: who, requestid: requestedId, amount_out: amount_out } = opData; + const { owner: who, requestid: requestedId, amount_out } = opData; result.value = `${amount_out}`; result.icon = 'hourglass-full'; result.details = who ? `@${who}, id: ${requestedId}` : null; break; case 'fill_transfer_from_savings': - let { from: fillwho, to: fillto, amount: fillamount, request_id: fillrequestId } = opData; + const { from: fillwho, to: fillto, amount: fillamount, request_id: fillrequestId } = opData; result.value = `${fillamount}`; result.icon = 'hourglass-full'; result.details = fillwho ? `@${fillwho} to @${fillto}, id: ${fillrequestId}` : null; break; case 'fill_vesting_withdraw': - let { from_account: pd_who, to_account: pd_to, deposited: deposited } = opData; + const { from_account: pd_who, to_account: pd_to, deposited } = opData; result.value = `${deposited}`; result.icon = 'hourglass-full'; @@ -223,20 +228,9 @@ export const groomingTransactionData = (transaction, hivePerMVests): CoinActivit return result; }; - export const groomingEngineHistory = (transaction: HistoryItem): CoinActivity | null => { - - const { - blockNumber, - operation, - timestamp, - symbol, - quantity, - authorperm, - memo, - from, - to - } = transaction; + const { blockNumber, operation, timestamp, symbol, quantity, authorperm, memo, from, to } = + transaction; const result: CoinActivity = { iconType: 'MaterialIcons', @@ -245,26 +239,22 @@ export const groomingEngineHistory = (transaction: HistoryItem): CoinActivity | created: new Date(timestamp).toISOString(), value: `${quantity} ${symbol}`, memo: memo || '', - details: authorperm ? authorperm : from && to ? `@${from} to @${to}` : null, + details: authorperm || (from && to ? `@${from} to @${to}` : null), icon: 'local-activity', - expires: '' + expires: '', }; - switch (result.textKey) { - case EngineOperations.TOKENS_CREATE: result.icon = 'fiber-new'; break; - case EngineOperations.TOKENS_TRANSFER: case EngineOperations.TOKENS_TRANSFER_OWNERSHIP: case EngineOperations.TOKENS_TRANSFER_TO_CONTRACT: result.icon = 'compare-arrows'; break; - case EngineOperations.TOKENS_TRANSFER_FROM_CONTRACT: case EngineOperations.TOKENS_TRANSFER_FEE: result.icon = 'attach-money'; @@ -279,11 +269,9 @@ export const groomingEngineHistory = (transaction: HistoryItem): CoinActivity | case EngineOperations.TOKENS_ENABLE_STAKING: case EngineOperations.TOKENS_ENABLE_DELEGATION: case EngineOperations.TOKENS_ISSUE: - result.icon = 'wb-iridescent'; break; - case EngineOperations.TOKENS_DELEGATE: case EngineOperations.TOKENS_STAKE: result.icon = 'change-history'; @@ -298,18 +286,16 @@ export const groomingEngineHistory = (transaction: HistoryItem): CoinActivity | // Group 8 case EngineOperations.TOKENS_UNDELEGATE_DONE: case EngineOperations.TOKENS_UNSTAKE_DONE: - result.icon = 'hourglass-full' + result.icon = 'hourglass-full'; case EngineOperations.TOKENS_UNDELEGATE_START: case EngineOperations.TOKENS_UNSTAKE_START: result.icon = 'hourglass-top'; break; } - return result; }; - export const groomingWalletData = async (user, globalProps, userCurrency) => { const walletData = {}; @@ -319,10 +305,10 @@ export const groomingWalletData = async (user, globalProps, userCurrency) => { const userdata = await getAccount(get(user, 'name')); - //const { accounts } = state; - //if (!accounts) { + // const { accounts } = state; + // if (!accounts) { // return walletData; - //} + // } walletData.rewardHiveBalance = parseToken(userdata.reward_hive_balance); walletData.rewardHbdBalance = parseToken(userdata.reward_hbd_balance); @@ -341,7 +327,7 @@ export const groomingWalletData = async (user, globalProps, userCurrency) => { walletData.savingBalance = parseToken(userdata.savings_balance); walletData.savingBalanceHbd = parseToken(userdata.savings_hbd_balance); - //TOOD: use base and quote from account.globalProps redux + // TOOD: use base and quote from account.globalProps redux const feedHistory = await getFeedHistory(); const base = parseToken(feedHistory.current_median_history.base); const quote = parseToken(feedHistory.current_median_history.quote); @@ -359,7 +345,7 @@ export const groomingWalletData = async (user, globalProps, userCurrency) => { walletData.estimatedValue = totalHive * pricePerHive + totalHbd; - //TODO: cache data in redux or fetch once on wallet startup + // TODO: cache data in redux or fetch once on wallet startup const ppHbd = await getCurrencyTokenRate(userCurrency, 'hbd'); const ppHive = await getCurrencyTokenRate(userCurrency, 'hive'); @@ -372,23 +358,23 @@ export const groomingWalletData = async (user, globalProps, userCurrency) => { const timeDiff = Math.abs(parseDate(userdata.next_vesting_withdrawal) - new Date()); walletData.nextVestingWithdrawal = Math.round(timeDiff / (1000 * 3600)); - //TOOD: transfer history can be separated from here + // TOOD: transfer history can be separated from here const op = utils.operationOrders; const ops = [ - op.transfer, //HIVE - op.author_reward, //HBD, HP - op.curation_reward, //HP - op.transfer_to_vesting, //HIVE, HP - op.withdraw_vesting, //HIVE, HP - op.interest, //HP - op.transfer_to_savings, //HIVE, HBD - op.transfer_from_savings, //HIVE, HBD - op.fill_convert_request, //HBD - op.fill_order, //HIVE, HBD - op.claim_reward_balance, //HP - op.sps_fund, //HBD - op.comment_benefactor_reward, //HP - op.return_vesting_delegation, //HP + op.transfer, // HIVE + op.author_reward, // HBD, HP + op.curation_reward, // HP + op.transfer_to_vesting, // HIVE, HP + op.withdraw_vesting, // HIVE, HP + op.interest, // HP + op.transfer_to_savings, // HIVE, HBD + op.transfer_from_savings, // HIVE, HBD + op.fill_convert_request, // HBD + op.fill_order, // HIVE, HBD + op.claim_reward_balance, // HP + op.sps_fund, // HBD + op.comment_benefactor_reward, // HP + op.return_vesting_delegation, // HP ]; const history = await getAccountHistory(get(user, 'name'), ops); @@ -415,7 +401,7 @@ export const fetchPendingRequests = async ( .filter((request) => request.sell_price.base.includes(coinSymbol)) .map((request) => { const { base, quote } = request?.sell_price || {}; - const orderid = request.orderid + const { orderid } = request; return { trxIndex: orderid, iconType: 'MaterialIcons', @@ -481,15 +467,15 @@ export const fetchCoinActivities = async ({ globalProps, startIndex, limit, - isEngine + isEngine, }: { - username: string, - assetId: string, - assetSymbol: string, - globalProps: GlobalProps, - startIndex: number, - limit: number, - isEngine?: boolean, + username: string; + assetId: string; + assetSymbol: string; + globalProps: GlobalProps; + startIndex: number; + limit: number; + isEngine?: boolean; }): Promise => { const op = operationOrders; let history = []; @@ -497,7 +483,7 @@ export const fetchCoinActivities = async ({ if (!isEngine) { switch (assetId) { case ASSET_IDS.ECENCY: { - //TODO: remove condition when we have a way to fetch paginated points data + // TODO: remove condition when we have a way to fetch paginated points data if (startIndex !== -1) { return []; } @@ -507,16 +493,16 @@ export const fetchCoinActivities = async ({ const completed = pointActivities && pointActivities.length ? pointActivities.map((item) => { - const { icon, iconType, textKey } = !!POINTS[item.type] - ? POINTS[item.type] : POINTS['default']; - return groomingPointsTransactionData({ - ...item, - icon, - iconType, - textKey + const { icon, iconType, textKey } = POINTS[item.type] + ? POINTS[item.type] + : POINTS.default; + return groomingPointsTransactionData({ + ...item, + icon, + iconType, + textKey, + }); }) - }, - ) : []; return completed; @@ -525,12 +511,12 @@ export const fetchCoinActivities = async ({ history = await getAccountHistory( username, [ - op.transfer, //HIVE - op.transfer_to_vesting, //HIVE, HP - op.withdraw_vesting, //HIVE, HP - op.transfer_to_savings, //HIVE, HBD - op.transfer_from_savings, //HIVE, HBD - op.fill_order, //HIVE, HBD + op.transfer, // HIVE + op.transfer_to_vesting, // HIVE, HP + op.withdraw_vesting, // HIVE, HP + op.transfer_to_savings, // HIVE, HBD + op.transfer_from_savings, // HIVE, HBD + op.fill_order, // HIVE, HBD ], startIndex, limit, @@ -540,13 +526,13 @@ export const fetchCoinActivities = async ({ history = await getAccountHistory( username, [ - op.transfer, //HIVE //HBD - op.author_reward, //HBD, HP - op.transfer_to_savings, //HIVE, HBD - op.transfer_from_savings, //HIVE, HBD - op.fill_convert_request, //HBD - op.fill_order, //HIVE, HBD - op.sps_fund, //HBD + op.transfer, // HIVE //HBD + op.author_reward, // HBD, HP + op.transfer_to_savings, // HIVE, HBD + op.transfer_from_savings, // HIVE, HBD + op.fill_convert_request, // HBD + op.fill_order, // HIVE, HBD + op.sps_fund, // HBD ], startIndex, limit, @@ -556,38 +542,41 @@ export const fetchCoinActivities = async ({ history = await getAccountHistory( username, [ - op.author_reward, //HBD, HP - op.curation_reward, //HP - op.transfer_to_vesting, //HIVE, HP - op.withdraw_vesting, //HIVE, HP - op.interest, //HP - op.claim_reward_balance, //HP - op.comment_benefactor_reward, //HP - op.return_vesting_delegation, //HP + op.author_reward, // HBD, HP + op.curation_reward, // HP + op.transfer_to_vesting, // HIVE, HP + op.withdraw_vesting, // HIVE, HP + op.interest, // HP + op.claim_reward_balance, // HP + op.comment_benefactor_reward, // HP + op.return_vesting_delegation, // HP ], startIndex, limit, ); break; - default: return []; - - + default: + return []; } const transfers = history.filter((tx) => transferTypes.includes(get(tx[1], 'op[0]', false))); transfers.sort(compare); - const activities = transfers.map((item) => groomingTransactionData(item, globalProps.hivePerMVests)); - const filterdActivities: CoinActivity[] = activities ? activities.filter((item) => { - return item && item.value && item.value.includes(assetSymbol); - }) : [] + const activities = transfers.map((item) => + groomingTransactionData(item, globalProps.hivePerMVests), + ); + const filterdActivities: CoinActivity[] = activities + ? activities.filter((item) => { + return item && item.value && item.value.includes(assetSymbol); + }) + : []; console.log('FILTERED comap', activities.length, filterdActivities.length); - //TODO: process pending requests as separate query //const pendingRequests = await fetchPendingRequests(username, coinSymbol); - return filterdActivities + // TODO: process pending requests as separate query //const pendingRequests = await fetchPendingRequests(username, coinSymbol); + return filterdActivities; } else { - //means asset is engine asset, maps response to + // means asset is engine asset, maps response to const engineHistory = await fetchEngineAccountHistory(username, assetSymbol, startIndex, limit); const activities = engineHistory.map(groomingEngineHistory); @@ -596,9 +585,12 @@ export const fetchCoinActivities = async ({ } }; - -const fetchEngineTokensData = async (username: string, hivePrice: number, vsCurrency: string, claimsCache: ClaimsCollection) => { - +const fetchEngineTokensData = async ( + username: string, + hivePrice: number, + vsCurrency: string, + claimsCache: ClaimsCollection, +) => { const engineCoinData: { [key: string]: CoinData } = {}; try { @@ -606,11 +598,16 @@ const fetchEngineTokensData = async (username: string, hivePrice: number, vsCurr if (engineData) { engineData.forEach((item) => { if (item) { - const balance = _processCachedData(item.symbol, item.balance, parseToken(item.unclaimedBalance), claimsCache); + const balance = _processCachedData( + item.symbol, + item.balance, + parseToken(item.unclaimedBalance), + claimsCache, + ); const ppToken = hivePrice * (item.tokenPrice || 1); const volume24h = hivePrice * (item.volume24h || 0); - const actions = [`${EngineActions.TRANSFER}_engine`] + const actions = [`${EngineActions.TRANSFER}_engine`]; if (item.delegationEnabled) { actions.push(`${EngineActions.DELEGATE}_engine`); @@ -621,161 +618,166 @@ const fetchEngineTokensData = async (username: string, hivePrice: number, vsCurr } if (item.stakingEnabled && item.balance > 0) { - actions.push(`${EngineActions.STAKE}_engine`) + actions.push(`${EngineActions.STAKE}_engine`); } if (item.stake) { - actions.push(`${EngineActions.UNSTAKE}_engine`) + actions.push(`${EngineActions.UNSTAKE}_engine`); } engineCoinData[item.symbol] = { name: item.name || '', symbol: item.symbol, iconUrl: item.icon || '', - balance: balance, + balance, estimateValue: balance * ppToken, - vsCurrency: vsCurrency, + vsCurrency, currentPrice: ppToken, unclaimedBalance: item.unclaimedBalance, isEngine: true, percentChange: item.percentChange, precision: item.precision, actions, - volume24h: volume24h, - extraDataPairs: [{ - dataKey: 'staked', - value: item.stake !== 0 ? `${item.stake}` : '0.00' - }, { - dataKey: 'delegations_in', - value: item.delegationsIn !== 0 ? `${item.delegationsIn}` : '0.00' - }, { - dataKey: 'delegations_out', - value: item.delegationsOut !== 0 ? `${item.delegationsOut}` : '0.00' - }] + volume24h, + extraDataPairs: [ + { + dataKey: 'staked', + value: item.stake !== 0 ? `${item.stake}` : '0.00', + }, + { + dataKey: 'delegations_in', + value: item.delegationsIn !== 0 ? `${item.delegationsIn}` : '0.00', + }, + { + dataKey: 'delegations_out', + value: item.delegationsOut !== 0 ? `${item.delegationsOut}` : '0.00', + }, + ], }; } }); } } catch (err) { - console.warn("failed to get engine tokens data", err); + console.warn('failed to get engine tokens data', err); } return engineCoinData; +}; - -} - - - -const _fetchSpkWalletData = async (username: string, hivePrice: number, vsCurrency: string, claimsCache: ClaimsCollection) => { +const _fetchSpkWalletData = async ( + username: string, + hivePrice: number, + vsCurrency: string, + claimsCache: ClaimsCollection, +) => { const spkWalletData: { [key: string]: CoinData } = {}; try { const spkWallet = await fetchSpkWallet(username); - const _price = parseFloat(spkWallet.tick) * hivePrice + const _price = parseFloat(spkWallet.tick) * hivePrice; if (spkWallet.spk) { - const _symbol = ASSET_IDS.SPK + const _symbol = ASSET_IDS.SPK; const _spkBalance = spkWallet.spk / 1000; spkWalletData[_symbol] = { - name: "SPK Network", + name: 'SPK Network', symbol: _symbol, balance: _spkBalance, estimateValue: _spkBalance * _price, - vsCurrency: vsCurrency, + vsCurrency, currentPrice: _price, isSpk: true, - actions: [TransferTypes.TRANSFER_SPK] - } + actions: [TransferTypes.TRANSFER_SPK], + }; } - const _available = spkWallet.drop?.availible + const _available = spkWallet.drop?.availible; if (_available) { - - //compile larynx token + // compile larynx token const _larBalance = spkWallet.balance / 1000; spkWalletData[ASSET_IDS.LARYNX] = { - name: ASSET_IDS.LARYNX + " Token", + name: `${ASSET_IDS.LARYNX} Token`, symbol: ASSET_IDS.LARYNX, balance: _larBalance, precision: _available.precision, estimateValue: _larBalance * _price, - vsCurrency: vsCurrency, + vsCurrency, currentPrice: _price, isSpk: true, actions: [ TransferTypes.TRANSFER_LARYNX, TransferTypes.POWER_UP_SPK, // TransferTypes.LOCK_LIQUIDITY - ] - } + ], + }; - - //compile larynx power + // compile larynx power const _larPower = spkWallet.poweredUp / 1000; const _grantedPwr = spkWallet.granted?.t ? spkWallet.granted.t / 1000 : 0; const _grantingPwr = spkWallet.granting?.t ? spkWallet.granting.t / 1000 : 0; - let _totalBalance = _larPower + _grantedPwr + _grantingPwr + const _totalBalance = _larPower + _grantedPwr + _grantingPwr; const _extraDataPairs: DataPair[] = []; if (spkWallet.power_downs) { _extraDataPairs.push({ dataKey: 'scheduled_power_downs', - value: Object.keys(spkWallet.power_downs).length - }) + value: Object.keys(spkWallet.power_downs).length, + }); } spkWalletData[ASSET_IDS.LARYNX_POWER] = { - name: ASSET_IDS.LARYNX + " Power", + name: `${ASSET_IDS.LARYNX} Power`, symbol: ASSET_IDS.LARYNX_POWER, balance: _larPower, precision: _available.precision, estimateValue: _larPower * _price, - vsCurrency: vsCurrency, + vsCurrency, currentPrice: _price, isSpk: true, - extraDataPairs: [..._extraDataPairs, - { - dataKey: 'delegated_larynx_power', - value: `${_grantedPwr.toFixed(3)} ${ASSET_IDS.LARYNX_POWER}` - }, { - dataKey: 'delegating_larynx_power', - value: `- ${_grantingPwr.toFixed(3)} ${ASSET_IDS.LARYNX_POWER}` - }, { - dataKey: 'total_larynx_power', - value: `${_totalBalance.toFixed(3)} ${ASSET_IDS.LARYNX_POWER}` - },], - actions: [ - TransferTypes.DELEGATE_SPK, - TransferTypes.POWER_DOWN_SPK, - ] - } + extraDataPairs: [ + ..._extraDataPairs, + { + dataKey: 'delegated_larynx_power', + value: `${_grantedPwr.toFixed(3)} ${ASSET_IDS.LARYNX_POWER}`, + }, + { + dataKey: 'delegating_larynx_power', + value: `- ${_grantingPwr.toFixed(3)} ${ASSET_IDS.LARYNX_POWER}`, + }, + { + dataKey: 'total_larynx_power', + value: `${_totalBalance.toFixed(3)} ${ASSET_IDS.LARYNX_POWER}`, + }, + ], + actions: [TransferTypes.DELEGATE_SPK, TransferTypes.POWER_DOWN_SPK], + }; } - - } catch (err) { - console.warn("Failed to get spk data", err); + console.warn('Failed to get spk data', err); } - return spkWalletData -} - - -const _processCachedData = (assetId: string, balance: number = 0, unclaimedBalance: number, claimsCache: ClaimsCollection) => { + return spkWalletData; +}; +const _processCachedData = ( + assetId: string, + balance = 0, + unclaimedBalance: number, + claimsCache: ClaimsCollection, +) => { const rewardHpStrToToken = (rewardStr: string) => { let tokenAmount = 0; - rewardStr.split(' ').forEach((str => { + rewardStr.split(' ').forEach((str) => { const asset = parseAsset(str); if (asset.symbol === assetId) { - tokenAmount = asset.amount + tokenAmount = asset.amount; } - })) + }); return tokenAmount; - } + }; if (claimsCache) { const _curTime = new Date().getTime(); @@ -800,14 +802,12 @@ const _processCachedData = (assetId: string, balance: number = 0, unclaimedBalan } if (_claim && (_claim.expiresAt || 0) > _curTime && rewardClaimed === unclaimedBalance) { - balance = balance + rewardClaimed; + balance += rewardClaimed; } - } - return balance -} - + return balance; +}; export const fetchCoinsData = async ({ coins, @@ -817,7 +817,7 @@ export const fetchCoinsData = async ({ globalProps, refresh, quotes, - claimsCache + claimsCache, }: { coins: CoinBase[]; currentAccount: any; @@ -826,9 +826,9 @@ export const fetchCoinsData = async ({ globalProps: GlobalProps; quotes: { [key: string]: QuoteItem }; refresh: boolean; - claimsCache: ClaimsCollection + claimsCache: ClaimsCollection; }): Promise<{ [key: string]: CoinData }> => { - const username = currentAccount.username; + const { username } = currentAccount; let coinData = {} as { [key: string]: CoinData }; const walletData = {}; @@ -836,16 +836,17 @@ export const fetchCoinsData = async ({ return walletData; } - //fetch latest global props if refresh or data not available + // fetch latest global props if refresh or data not available const { base, quote, hivePerMVests } = refresh || !globalProps || !globalProps.hivePerMVests ? await fetchGlobalProps() : globalProps; - //TODO: Use already available accoutn for frist wallet start + // TODO: Use already available accoutn for frist wallet start const userdata = refresh ? await getAccount(username) : currentAccount; - const _pointsSummary = refresh || !currentAccount?.pointsSummary ? await getPointsSummary(username) : currentAccount.pointsSummary; - //TODO: cache data in redux or fetch once on wallet startup - const _prices = !refresh && quotes ? quotes : await getLatestQuotes(currencyRate); //TODO: figure out a way to handle other currencies - - + const _pointsSummary = + refresh || !currentAccount?.pointsSummary + ? await getPointsSummary(username) + : currentAccount.pointsSummary; + // TODO: cache data in redux or fetch once on wallet startup + const _prices = !refresh && quotes ? quotes : await getLatestQuotes(currencyRate); // TODO: figure out a way to handle other currencies coins.forEach((coinBase) => { switch (coinBase.id) { @@ -854,21 +855,26 @@ export const fetchCoinsData = async ({ let balance = _pointsSummary.points ? parseFloat(_pointsSummary.points) : 0; balance = _processCachedData(coinBase.id, balance, unclaimedFloat, claimsCache); - const unclaimedBalance = unclaimedFloat ? unclaimedFloat + ' Points' : ''; + const unclaimedBalance = unclaimedFloat ? `${unclaimedFloat} Points` : ''; const ppEstm = _prices[coinBase.id].price; coinData[coinBase.id] = { balance: Math.round(balance * 1000) / 1000, estimateValue: balance * ppEstm, - vsCurrency: vsCurrency, + vsCurrency, currentPrice: ppEstm, - unclaimedBalance: unclaimedBalance, + unclaimedBalance, actions: ECENCY_ACTIONS, }; break; } case ASSET_IDS.HIVE: { - const balance = _processCachedData(coinBase.id, parseToken(userdata.balance), parseToken(userdata.reward_hive_balance), claimsCache); + const balance = _processCachedData( + coinBase.id, + parseToken(userdata.balance), + parseToken(userdata.reward_hive_balance), + claimsCache, + ); const savings = parseToken(userdata.savings_balance); const ppHive = _prices[coinBase.id].price; @@ -876,7 +882,7 @@ export const fetchCoinsData = async ({ balance: Math.round(balance * 1000) / 1000, estimateValue: (balance + savings) * ppHive, savings: Math.round(savings * 1000) / 1000, - vsCurrency: vsCurrency, + vsCurrency, currentPrice: ppHive, unclaimedBalance: '', actions: HIVE_ACTIONS, @@ -885,7 +891,12 @@ export const fetchCoinsData = async ({ } case ASSET_IDS.HBD: { - const balance = _processCachedData(coinBase.id, parseToken(userdata.hbd_balance), parseToken(userdata.reward_hbd_balance), claimsCache); + const balance = _processCachedData( + coinBase.id, + parseToken(userdata.hbd_balance), + parseToken(userdata.reward_hbd_balance), + claimsCache, + ); const savings = parseToken(userdata.savings_hbd_balance); const ppHbd = _prices[coinBase.id].price; @@ -893,7 +904,7 @@ export const fetchCoinsData = async ({ balance: Math.round(balance * 1000) / 1000, estimateValue: (balance + savings) * ppHbd, savings: Math.round(savings * 1000) / 1000, - vsCurrency: vsCurrency, + vsCurrency, currentPrice: ppHbd, unclaimedBalance: '', actions: HBD_ACTIONS, @@ -901,16 +912,20 @@ export const fetchCoinsData = async ({ break; } case ASSET_IDS.HP: { - let balance = Math.round(vestsToHp(parseToken(userdata.vesting_shares), hivePerMVests) * 1000) / 1000; - balance = _processCachedData(coinBase.id, balance, parseToken(userdata.vesting_shares), claimsCache); + balance = _processCachedData( + coinBase.id, + balance, + parseToken(userdata.vesting_shares), + claimsCache, + ); const receivedHP = vestsToHp(parseToken(userdata.received_vesting_shares), hivePerMVests); const delegatedHP = vestsToHp(parseToken(userdata.delegated_vesting_shares), hivePerMVests); - //agggregate claim button text + // agggregate claim button text const _getBalanceStr = (val: number, cur: string) => val ? Math.round(val * 1000) / 1000 + cur : ''; const unclaimedBalance = [ @@ -922,25 +937,26 @@ export const fetchCoinsData = async ({ '', ); - //calculate power down + // calculate power down const pwrDwnHoursLeft = getHoursDifferntial( - parseDate(userdata.next_vesting_withdrawal), new Date()) + parseDate(userdata.next_vesting_withdrawal), + new Date(), + ); const isPoweringDown = pwrDwnHoursLeft > 0; - const nextVestingSharesWithdrawal = isPoweringDown ? Math.min( - parseAsset(userdata.vesting_withdraw_rate).amount, - (Number(userdata.to_withdraw) - Number(userdata.withdrawn)) / 1e6, - ) + parseAsset(userdata.vesting_withdraw_rate).amount, + (Number(userdata.to_withdraw) - Number(userdata.withdrawn)) / 1e6, + ) : 0; const nextVestingSharesWithdrawalHive = isPoweringDown ? vestsToHp(nextVestingSharesWithdrawal, hivePerMVests) : 0; - const estimateVoteValueStr = '$ ' + getEstimatedAmount(userdata, globalProps); + const estimateVoteValueStr = `$ ${getEstimatedAmount(userdata, globalProps)}`; - //aaggregate extra data pairs + // aaggregate extra data pairs const extraDataPairs: DataPair[] = []; if (delegatedHP) { @@ -963,7 +979,7 @@ export const fetchCoinsData = async ({ extraDataPairs.push({ dataKey: 'powering_down_hive_power', value: `- ${nextVestingSharesWithdrawalHive.toFixed(3)} HP`, - subValue: Math.round(pwrDwnHoursLeft) + 'h' + subValue: `${Math.round(pwrDwnHoursLeft)}h`, }); } @@ -988,7 +1004,7 @@ export const fetchCoinsData = async ({ balance: Math.round(balance * 1000) / 1000, estimateValue: balance * ppHive, unclaimedBalance, - vsCurrency: vsCurrency, + vsCurrency, currentPrice: ppHive, actions: HIVE_POWER_ACTIONS, extraDataPairs: [ @@ -1016,13 +1032,21 @@ export const fetchCoinsData = async ({ } }); - - const engineCoinsData = await fetchEngineTokensData(username, _prices.hive.price, vsCurrency, claimsCache); - const spkWalletData = await _fetchSpkWalletData(username, _prices.hive.price, vsCurrency, claimsCache); + const engineCoinsData = await fetchEngineTokensData( + username, + _prices.hive.price, + vsCurrency, + claimsCache, + ); + const spkWalletData = await _fetchSpkWalletData( + username, + _prices.hive.price, + vsCurrency, + claimsCache, + ); coinData = { ...coinData, ...engineCoinsData, ...spkWalletData }; - - //TODO:discard unnessacry data processings towards the end of PR + // TODO:discard unnessacry data processings towards the end of PR walletData.rewardHiveBalance = parseToken(userdata.reward_hive_balance); walletData.rewardHbdBalance = parseToken(userdata.reward_hbd_balance); walletData.rewardVestingHive = parseToken(userdata.reward_vesting_hive); @@ -1079,7 +1103,8 @@ export const groomingPointsTransactionData = (transaction) => { ...transaction, }; - result.details = transaction.sender ? `from @${transaction.sender}` + result.details = transaction.sender + ? `from @${transaction.sender}` : transaction.receiver && `to @${transaction.receiver}`; result.value = `${transaction.amount} Points`;