From ba3e2f0f2cfd047514844784d07da0fbaaedd575 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Thu, 28 Sep 2023 17:02:18 +0500 Subject: [PATCH 001/111] added upload package --- android/app/proguard-rules.pro | 3 +++ package.json | 1 + yarn.lock | 5 +++++ 3 files changed, 9 insertions(+) diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro index 0ef709f33..667ed30e4 100644 --- a/android/app/proguard-rules.pro +++ b/android/app/proguard-rules.pro @@ -14,3 +14,6 @@ # -keep class com.swmansion.reanimated.** { *; } # -keep class com.facebook.react.turbomodule.** { *; } + +# config for rn background upload +-keep class net.gotev.uploadservice.** { *; } diff --git a/package.json b/package.json index 0fe05db1f..f361343ab 100644 --- a/package.json +++ b/package.json @@ -102,6 +102,7 @@ "react-native-animatable": "^1.3.3", "react-native-autoheight-webview": "^1.5.8", "react-native-background-timer": "^2.4.1", + "react-native-background-upload": "^6.6.0", "react-native-bootsplash": "^4.3.2", "react-native-camera": "^4.2.1", "react-native-chart-kit": "^6.11.0", diff --git a/yarn.lock b/yarn.lock index bf7e51327..9c6f75340 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8918,6 +8918,11 @@ react-native-background-timer@^2.4.1: resolved "https://registry.yarnpkg.com/react-native-background-timer/-/react-native-background-timer-2.4.1.tgz#a3bc1cafa8c1e3aeefd0611de120298b67978a0f" integrity sha512-TE4Kiy7jUyv+hugxDxitzu38sW1NqjCk4uE5IgU2WevLv7sZacaBc6PZKOShNRPGirLl1NWkaG3LDEkdb9Um5g== +react-native-background-upload@^6.6.0: + version "6.6.0" + resolved "https://registry.yarnpkg.com/react-native-background-upload/-/react-native-background-upload-6.6.0.tgz#7c081f4260d16e7a416522c3622b81938ad799c8" + integrity sha512-adfOJmeO3GmPmc53cdHYWp5eTGKagk/AhkraSoQ89BHRwBWrtRQ29NN9sm2CLezBYrSQWg0W47C8TaowtYZ1LQ== + react-native-blob-util@^0.16.0: version "0.16.4" resolved "https://registry.yarnpkg.com/react-native-blob-util/-/react-native-blob-util-0.16.4.tgz#eeb0e28f6fa6ecb357c10f154be3d2e66c010f62" From 8d55a0f6a13fc36e52e7544ca821eca238dd388e Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Thu, 28 Sep 2023 17:03:01 +0500 Subject: [PATCH 002/111] test integration of background upload --- .../container/uploadsGalleryModal.tsx | 103 +++++++++++++----- 1 file changed, 75 insertions(+), 28 deletions(-) diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 7ae1422e2..99453bd22 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -1,6 +1,6 @@ import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'; import { useIntl } from 'react-intl'; -import { Alert, AlertButton } from 'react-native'; +import { Alert, AlertButton, Platform } from 'react-native'; import ImagePicker, { Image } from 'react-native-image-crop-picker'; import RNHeicConverter from 'react-native-heic-converter'; import { openSettings } from 'react-native-permissions'; @@ -13,6 +13,10 @@ import { delay, extractFilenameFromPath } from '../../../utils/editor'; import showLoginAlert from '../../../utils/showLoginAlert'; import { useMediaQuery, useMediaUploadMutation } from '../../../providers/queries'; import { showActionModal } from '../../../redux/actions/uiAction'; +import Upload, { UploadOptions } from 'react-native-background-upload' +import Config from 'react-native-config'; +import { signImage } from '../../../providers/hive/dhive'; +import reactotron from 'reactotron-react-native'; export interface UploadsGalleryModalRef { showModal: () => void; @@ -62,7 +66,7 @@ export const UploadsGalleryModal = forwardRef( const dispatch = useAppDispatch(); const mediaQuery = useMediaQuery(); - const mediaUploadMutation = useMediaUploadMutation(); + // const mediaUploadMutation = useMediaUploadMutation(); const pendingInserts = useRef([]); @@ -221,34 +225,77 @@ export const UploadsGalleryModal = forwardRef( setIsAddingToUploads(true); } - await mediaUploadMutation.mutateAsync( - { - media, - addToUploads: !shouldInsert, + let sign = await signImage(media, currentAccount, pinCode); + const _options:UploadOptions = { + url: `${Config.NEW_IMAGE_API}/hs/${sign}`, + path: Platform.select({ + ios: 'file://' + media.path, + android: media.path.replace('file://', '') + }), + method: 'POST', + type: 'multipart', + maxRetries: 2, // set retry count (Android only). Default 2 + headers: { + 'Authorization': Config.NEW_IMAGE_API, // Config.NEW_IMAGE_API + 'Content-Type': 'multipart/form-data', }, - { - onSuccess: (data) => { - console.log('upload successfully', data, media, shouldInsert); - if (data && data.url && shouldInsert) { - _handleMediaInsertion({ - filename: media.filename, - url: data.url, - text: '', - status: MediaInsertStatus.READY, - }); - } - }, - onSettled: () => { - if (setIsUploading) { - setIsUploading(false); - } - setIsAddingToUploads(false); - }, - onError: (err) => { - throw err; - }, + field: 'uploaded_media', + // Below are options only supported on Android + notification: { + enabled: true }, - ); + useUtf8Charset: true + } + + Upload.startUpload(_options).then((uploadId) => { + reactotron.log('Upload started') + Upload.addListener('progress', uploadId, (data) => { + reactotron.log(`Progress: ${data.progress}%`, data) + }) + Upload.addListener('error', uploadId, (data) => { + reactotron.log(`Error`, data) + }) + Upload.addListener('cancelled', uploadId, (data) => { + reactotron.log(`Cancelled!`, data) + }) + Upload.addListener('completed', uploadId, (data) => { + // data includes responseCode: number and responseBody: Object + reactotron.log('Completed!', data) + }) + }).catch((err)=>{ + reactotron.log('error', err) + }) + + // await mediaUploadMutation.mutateAsync( + // { + // media, + // addToUploads: !shouldInsert, + // }, + // { + // onSuccess: (data) => { + // console.log('upload successfully', data, media, shouldInsert); + // if (data && data.url && shouldInsert) { + // _handleMediaInsertion({ + // filename: media.filename, + // url: data.url, + // text: '', + // status: MediaInsertStatus.READY, + // }); + // } + // }, + // onSettled: () => { + // if (setIsUploading) { + // setIsUploading(false); + // } + // setIsAddingToUploads(false); + // }, + // onError: (err) => { + // throw err; + // }, + // }, + // ); + + } catch (error) { console.log('error while uploading image : ', error); From bede7d2bcaab77a4c1bc78f0f9072c25db6263d2 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Wed, 11 Oct 2023 18:19:30 +0500 Subject: [PATCH 003/111] replacing placeholder after upload --- ios/Podfile.lock | 6 ++++ .../container/uploadsGalleryModal.tsx | 32 ++++++++++++++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/ios/Podfile.lock b/ios/Podfile.lock index d26aee693..c33caa310 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -445,6 +445,8 @@ PODS: - glog - react-native-background-timer (2.4.1): - React-Core + - react-native-background-upload (6.6.0): + - React - react-native-camera (4.2.1): - React-Core - react-native-camera/RCT (= 4.2.1) @@ -726,6 +728,7 @@ DEPENDENCIES: - React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`) - React-logger (from `../node_modules/react-native/ReactCommon/logger`) - react-native-background-timer (from `../node_modules/react-native-background-timer`) + - react-native-background-upload (from `../node_modules/react-native-background-upload`) - react-native-camera (from `../node_modules/react-native-camera`) - "react-native-cameraroll (from `../node_modules/@react-native-community/cameraroll`)" - react-native-config (from `../node_modules/react-native-config`) @@ -879,6 +882,8 @@ EXTERNAL SOURCES: :path: "../node_modules/react-native/ReactCommon/logger" react-native-background-timer: :path: "../node_modules/react-native-background-timer" + react-native-background-upload: + :path: "../node_modules/react-native-background-upload" react-native-camera: :path: "../node_modules/react-native-camera" react-native-cameraroll: @@ -1049,6 +1054,7 @@ SPEC CHECKSUMS: React-jsinspector: 1c34fea1868136ecde647bc11fae9266d4143693 React-logger: e9f407f9fdf3f3ce7749ae6f88affe63e8446019 react-native-background-timer: 17ea5e06803401a379ebf1f20505b793ac44d0fe + react-native-background-upload: 7c608537f87106c93530a3a19a853afd55466823 react-native-camera: 3eae183c1d111103963f3dd913b65d01aef8110f react-native-cameraroll: e2917a5e62da9f10c3d525e157e25e694d2d6dfa react-native-config: 86038147314e2e6d10ea9972022aa171e6b1d4d8 diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 99453bd22..686b706bb 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -225,13 +225,17 @@ export const UploadsGalleryModal = forwardRef( setIsAddingToUploads(true); } + + let sign = await signImage(media, currentAccount, pinCode); - const _options:UploadOptions = { + + + const _options: UploadOptions = { url: `${Config.NEW_IMAGE_API}/hs/${sign}`, path: Platform.select({ ios: 'file://' + media.path, android: media.path.replace('file://', '') - }), + }), method: 'POST', type: 'multipart', maxRetries: 2, // set retry count (Android only). Default 2 @@ -248,22 +252,42 @@ export const UploadsGalleryModal = forwardRef( } Upload.startUpload(_options).then((uploadId) => { + reactotron.log('Upload started') + + //TODO: manage insertions here + Upload.addListener('progress', uploadId, (data) => { reactotron.log(`Progress: ${data.progress}%`, data) }) Upload.addListener('error', uploadId, (data) => { reactotron.log(`Error`, data) + throw data.error; }) Upload.addListener('cancelled', uploadId, (data) => { reactotron.log(`Cancelled!`, data) + throw new Error("Upload Cancelled") }) Upload.addListener('completed', uploadId, (data) => { // data includes responseCode: number and responseBody: Object reactotron.log('Completed!', data) + console.log('upload successfully', data, media, shouldInsert); + const _respData = JSON.parse(data.responseBody); + if (_respData && _respData.url && shouldInsert) { + _handleMediaInsertion({ + filename: media.filename, + url: _respData.url, + text: '', + status: MediaInsertStatus.READY, + }); + } + + setIsUploading(false); + setIsAddingToUploads(false); }) - }).catch((err)=>{ + }).catch((err) => { reactotron.log('error', err) + throw err; }) // await mediaUploadMutation.mutateAsync( @@ -351,7 +375,7 @@ export const UploadsGalleryModal = forwardRef( let body = error.message || JSON.stringify(error); let action: AlertButton = { text: intl.formatMessage({ id: 'alert.okay' }), - onPress: () => {}, + onPress: () => { }, }; switch (error.code) { From 7db5bd79a505c57917e81c6b35c4705db03eda30 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 13 Oct 2023 18:05:53 +0500 Subject: [PATCH 004/111] setup better dev environment for better testing media uploads --- src/components/markdownEditor/children/editorToolbar.tsx | 7 +++++-- src/navigation/stackNavigator.tsx | 4 ++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/components/markdownEditor/children/editorToolbar.tsx b/src/components/markdownEditor/children/editorToolbar.tsx index 1bae2b805..affb941fc 100644 --- a/src/components/markdownEditor/children/editorToolbar.tsx +++ b/src/components/markdownEditor/children/editorToolbar.tsx @@ -45,8 +45,8 @@ export const EditorToolbar = ({ const shouldHideExtension = useRef(false); const extensionHeight = useRef(0); - const [isExtensionVisible, setIsExtensionVisible] = useState(false); - + const [isExtensionVisible, setIsExtensionVisible] = useState(false); + const [isKeyboardVisible, setKeyboardVisible] = useState(false); useEffect(() => { @@ -57,6 +57,9 @@ export const EditorToolbar = ({ setKeyboardVisible(false); // or some other action }); + //TODO: set to false before PR + _showUploadsExtension(); + return () => { keyboardDidHideListener.remove(); keyboardDidShowListener.remove(); diff --git a/src/navigation/stackNavigator.tsx b/src/navigation/stackNavigator.tsx index 327f2f81d..411135438 100644 --- a/src/navigation/stackNavigator.tsx +++ b/src/navigation/stackNavigator.tsx @@ -43,8 +43,9 @@ const RootStack = createNativeStackNavigator(); const MainStack = createNativeStackNavigator(); const MainStackNavigator = () => { + //TODO: remove initialRoute before PR return ( - + @@ -88,7 +89,6 @@ export const StackNavigator = ({ initRoute }) => { screenOptions={{ headerShown: false, animation: 'slide_from_bottom' }} > - From 28732671b4c47de5cb3fc4afe89092c09d450851 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 13 Oct 2023 18:56:57 +0500 Subject: [PATCH 005/111] intgrated upload service with uploads mutation --- .../container/uploadsGalleryModal.tsx | 123 ++++-------------- src/providers/queries/editorQueries.ts | 68 +++++++++- 2 files changed, 91 insertions(+), 100 deletions(-) diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 686b706bb..d7f5bcf71 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -1,6 +1,6 @@ import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'; import { useIntl } from 'react-intl'; -import { Alert, AlertButton, Platform } from 'react-native'; +import { Alert, AlertButton } from 'react-native'; import ImagePicker, { Image } from 'react-native-image-crop-picker'; import RNHeicConverter from 'react-native-heic-converter'; import { openSettings } from 'react-native-permissions'; @@ -13,10 +13,6 @@ import { delay, extractFilenameFromPath } from '../../../utils/editor'; import showLoginAlert from '../../../utils/showLoginAlert'; import { useMediaQuery, useMediaUploadMutation } from '../../../providers/queries'; import { showActionModal } from '../../../redux/actions/uiAction'; -import Upload, { UploadOptions } from 'react-native-background-upload' -import Config from 'react-native-config'; -import { signImage } from '../../../providers/hive/dhive'; -import reactotron from 'reactotron-react-native'; export interface UploadsGalleryModalRef { showModal: () => void; @@ -66,7 +62,7 @@ export const UploadsGalleryModal = forwardRef( const dispatch = useAppDispatch(); const mediaQuery = useMediaQuery(); - // const mediaUploadMutation = useMediaUploadMutation(); + const mediaUploadMutation = useMediaUploadMutation(); const pendingInserts = useRef([]); @@ -227,97 +223,34 @@ export const UploadsGalleryModal = forwardRef( - let sign = await signImage(media, currentAccount, pinCode); - - - const _options: UploadOptions = { - url: `${Config.NEW_IMAGE_API}/hs/${sign}`, - path: Platform.select({ - ios: 'file://' + media.path, - android: media.path.replace('file://', '') - }), - method: 'POST', - type: 'multipart', - maxRetries: 2, // set retry count (Android only). Default 2 - headers: { - 'Authorization': Config.NEW_IMAGE_API, // Config.NEW_IMAGE_API - 'Content-Type': 'multipart/form-data', + await mediaUploadMutation.mutateAsync( + { + media, + addToUploads: !shouldInsert, }, - field: 'uploaded_media', - // Below are options only supported on Android - notification: { - enabled: true + { + onSuccess: (data) => { + console.log('upload successfully', data, media, shouldInsert); + if (data && data.url && shouldInsert) { + _handleMediaInsertion({ + filename: media.filename, + url: data.url, + text: '', + status: MediaInsertStatus.READY, + }); + } + }, + onSettled: () => { + if (setIsUploading) { + setIsUploading(false); + } + setIsAddingToUploads(false); + }, + onError: (err) => { + throw err; + }, }, - useUtf8Charset: true - } - - Upload.startUpload(_options).then((uploadId) => { - - reactotron.log('Upload started') - - //TODO: manage insertions here - - Upload.addListener('progress', uploadId, (data) => { - reactotron.log(`Progress: ${data.progress}%`, data) - }) - Upload.addListener('error', uploadId, (data) => { - reactotron.log(`Error`, data) - throw data.error; - }) - Upload.addListener('cancelled', uploadId, (data) => { - reactotron.log(`Cancelled!`, data) - throw new Error("Upload Cancelled") - }) - Upload.addListener('completed', uploadId, (data) => { - // data includes responseCode: number and responseBody: Object - reactotron.log('Completed!', data) - console.log('upload successfully', data, media, shouldInsert); - const _respData = JSON.parse(data.responseBody); - if (_respData && _respData.url && shouldInsert) { - _handleMediaInsertion({ - filename: media.filename, - url: _respData.url, - text: '', - status: MediaInsertStatus.READY, - }); - } - - setIsUploading(false); - setIsAddingToUploads(false); - }) - }).catch((err) => { - reactotron.log('error', err) - throw err; - }) - - // await mediaUploadMutation.mutateAsync( - // { - // media, - // addToUploads: !shouldInsert, - // }, - // { - // onSuccess: (data) => { - // console.log('upload successfully', data, media, shouldInsert); - // if (data && data.url && shouldInsert) { - // _handleMediaInsertion({ - // filename: media.filename, - // url: data.url, - // text: '', - // status: MediaInsertStatus.READY, - // }); - // } - // }, - // onSettled: () => { - // if (setIsUploading) { - // setIsUploading(false); - // } - // setIsAddingToUploads(false); - // }, - // onError: (err) => { - // throw err; - // }, - // }, - // ); + ); } catch (error) { diff --git a/src/providers/queries/editorQueries.ts b/src/providers/queries/editorQueries.ts index 04506ba95..11ed9c552 100644 --- a/src/providers/queries/editorQueries.ts +++ b/src/providers/queries/editorQueries.ts @@ -16,6 +16,9 @@ import { import { MediaItem, Snippet } from '../ecency/ecency.types'; import { signImage } from '../hive/dhive'; import QUERIES from './queryKeys'; +import Upload, { UploadOptions } from 'react-native-background-upload' +import Config from 'react-native-config'; +import { Platform } from 'react-native'; interface SnippetMutationVars { id: string | null; @@ -84,14 +87,69 @@ export const useMediaUploadMutation = () => { const currentAccount = useAppSelector((state) => state.account.currentAccount); const pinCode = useAppSelector((state) => state.application.pin); + const _uploadMedia = ({ media }: MediaUploadVars) => { + + return new Promise(async (resolve, reject) => { + + try { + let sign = await signImage(media, currentAccount, pinCode); + + const _options: UploadOptions = { + url: `${Config.NEW_IMAGE_API}/hs/${sign}`, + path: Platform.select({ + ios: 'file://' + media.path, + android: media.path.replace('file://', '') + }), + method: 'POST', + type: 'multipart', + maxRetries: 2, // set retry count (Android only). Default 2 + headers: { + 'Authorization': Config.NEW_IMAGE_API, // Config.NEW_IMAGE_API + 'Content-Type': 'multipart/form-data', + }, + field: 'uploaded_media', + // Below are options only supported on Android + notification: { + enabled: true + }, + useUtf8Charset: true + } + + const uploadId = await Upload.startUpload(_options) + + console.log('Upload started', uploadId) + + Upload.addListener('progress', uploadId, (data) => { + console.log(`Progress: ${data.progress}%`, data) + }) + Upload.addListener('error', uploadId, (data) => { + console.log(`Error`, data) + throw data.error; + }) + Upload.addListener('cancelled', uploadId, (data) => { + console.log(`Cancelled!`, data) + throw new Error("Upload Cancelled") + }) + Upload.addListener('completed', uploadId, (data) => { + // data includes responseCode: number and responseBody: Object + console.log('Completed!', data) + const _respData = JSON.parse(data.responseBody); + resolve(_respData) + }) + } catch (err) { + console.warn("Meida Upload Failed", err); + reject(err) + } + }) + } + + return useMutation( - async ({ media }) => { - console.log('uploading media', media); - let sign = await signImage(media, currentAccount, pinCode); - return await uploadImage(media, currentAccount.name, sign); + (vars) => { + + return _uploadMedia(vars); }, { - retry: 3, onSuccess: (response, { addToUploads }) => { if (addToUploads && response && response.url) { console.log('adding image to gallery', response.url); From ec6858b275ca3db39159d3fb151541fde9ae95ef Mon Sep 17 00:00:00 2001 From: noumantahir Date: Wed, 18 Oct 2023 18:26:27 +0500 Subject: [PATCH 006/111] spk api draft --- src/providers/speak/speak.ts | 224 +++++++++++++++++++++++++++++++++++ 1 file changed, 224 insertions(+) create mode 100644 src/providers/speak/speak.ts diff --git a/src/providers/speak/speak.ts b/src/providers/speak/speak.ts new file mode 100644 index 000000000..d64344351 --- /dev/null +++ b/src/providers/speak/speak.ts @@ -0,0 +1,224 @@ +import * as tus from "tus-js-client"; +import axios from "axios"; +import { getDecodedMemo } from "../../helper/hive-signer"; +import { ThreeSpeakVideo } from "./types"; + +const studioEndPoint = "https://studio.3speak.tv"; +const tusEndPoint = "https://uploads.3speak.tv/files/"; +const client = axios.create({}); + +export const threespeakAuth = async (username: string) => { + try { + let response = await client.get( + `${studioEndPoint}/mobile/login?username=${username}&hivesigner=true`, + { + withCredentials: false, + headers: { + "Content-Type": "application/json" + } + } + ); + const memo_string = response.data.memo; + let { memoDecoded } = await getDecodedMemo(username, memo_string); + + memoDecoded = memoDecoded.replace("#", ""); + return memoDecoded; + } catch (err) { + console.error(new Error("[3Speak auth] Failed to login")); + throw err; + } + }; + + export const getTokenValidated = async (jwt: string, username: string) => { + try { + let response = await client.get( + `${studioEndPoint}/mobile/login?username=${username}&access_token=${jwt}`, + { + withCredentials: false, + headers: { + "Content-Type": "application/json" + } + } + ); + return response.data; + } catch (err) { + console.log(err); + throw err; + } + }; + + export const uploadVideoInfo = async ( + oFilename: string, + fileSize: number, + videoUrl: string, + thumbnailUrl: string, + username: string, + duration: string + ) => { + const token = await threespeakAuth(username); + try { + const { data } = await axios.post( + `${studioEndPoint}/mobile/api/upload_info?app=ecency`, + { + filename: videoUrl, + oFilename: oFilename, + size: fileSize, + duration, + thumbnail: thumbnailUrl, + isReel: false, + owner: username + }, + { + withCredentials: false, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}` + } + } + ); + return data; + } catch (e) { + console.error(e); + throw e; + } + }; + + export const getAllVideoStatuses = async (username: string) => { + const token = await threespeakAuth(username); + try { + let response = await client.get(`${studioEndPoint}/mobile/api/my-videos`, { + withCredentials: false, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}` + } + }); + return response.data; + } catch (err) { + console.error(new Error("[3Speak video] Failed to get videos")); + + throw err; + } + }; + + export const updateSpeakVideoInfo = async ( + username: string, + postBody: string, + videoId: string, + title: string, + tags: string[], + isNsfwC: boolean + ) => { + const token = await threespeakAuth(username); + + const data = { + videoId: videoId, + title: title, + description: postBody, + isNsfwContent: isNsfwC, + tags_v2: tags + }; + + const headers = { + "Content-Type": "application/json", + Authorization: `Bearer ${token}` + }; + + try { + await axios.post(`${studioEndPoint}/mobile/api/update_info`, data, { headers }); + } catch (e) { + console.error(e); + } + }; + + export const markAsPublished = async (username: string, videoId: string) => { + const token = await threespeakAuth(username); + const data = { + videoId + }; + + const headers = { + "Content-Type": "application/json", + Authorization: `Bearer ${token}` + }; + + axios + .post(`${studioEndPoint}/mobile/api/my-videos/iPublished`, data, { headers }) + .then((response) => {}) + .catch((error) => { + console.error("Error:", error); + }); + }; + + + export const uploadVideo = async (media, onUploadProgress) => { + try { + const file = { + uri: media.path, + type: media.mime, + name: media.filename || `img_${Math.random()}.mp4`, + size: media.size, + }; + + const fData = new FormData(); + fData.append('file', file); + + const res = await axios.post(tusEndPoint, fData, { + onUploadProgress + }); + if (!res || !res.data) { + throw new Error('Returning response missing media data'); + } + return res.data; + } catch (error) { + console.warn('Image upload failed', error); + throw error; + } + }; + +// export const uploadFile = async ( +// file: File, +// type: string, +// progressCallback: (percentage: number) => void +// ) => { +// return new Promise<{ +// fileUrl: string; +// fileName: string; +// fileSize: number; +// }>((resolve, reject) => { +// let vPercentage = 0; +// let tPercentage = 0; + +// const upload: any = new tus.Upload(file, { +// endpoint: tusEndPoint, +// retryDelays: [0, 3000, 5000, 10000, 20000], +// metadata: { +// filename: file.name, +// filetype: file.type +// }, +// onError: function (error: Error) { +// reject(error); +// }, +// onProgress: function (bytesUploaded: number, bytesTotal: number) { +// if (type === "video") { +// vPercentage = Number(((bytesUploaded / bytesTotal) * 100).toFixed(2)); +// progressCallback(vPercentage); +// } else { +// tPercentage = Number(((bytesUploaded / bytesTotal) * 100).toFixed(2)); +// progressCallback(tPercentage); +// } +// }, +// onSuccess: function () { +// let fileUrl = upload?.url.replace(tusEndPoint, ""); +// const result = { +// fileUrl, +// fileName: upload.file?.name || "", +// fileSize: upload.file?.size || 0 +// }; +// resolve(result); +// } +// }); +// upload.start(); +// }); +// }; + \ No newline at end of file From 6c02c4ebe03f6a5df1dc14e86db15cdc00de080a Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 19 Oct 2023 14:10:12 +0500 Subject: [PATCH 007/111] working three speak auth and memo decode --- package.json | 2 +- src/providers/speak/speak.ts | 287 +++++++++++++++-------------- src/providers/speak/speak.types.ts | 3 + yarn.lock | 8 +- 4 files changed, 158 insertions(+), 142 deletions(-) create mode 100644 src/providers/speak/speak.types.ts diff --git a/package.json b/package.json index 8d04284c7..5a982d656 100644 --- a/package.json +++ b/package.json @@ -82,7 +82,7 @@ "domain-browser": "^1.1.1", "events": "^1.0.0", "hive-uri": "^0.2.5", - "hivesigner": "^3.2.7", + "hivesigner": "^3.3.4", "https-browserify": "~0.0.0", "intl": "^1.2.5", "jsc-android": "^241213.1.0", diff --git a/src/providers/speak/speak.ts b/src/providers/speak/speak.ts index d64344351..d5c67dc83 100644 --- a/src/providers/speak/speak.ts +++ b/src/providers/speak/speak.ts @@ -1,181 +1,171 @@ -import * as tus from "tus-js-client"; import axios from "axios"; -import { getDecodedMemo } from "../../helper/hive-signer"; -import { ThreeSpeakVideo } from "./types"; +import { getDigitPinCode } from "../hive/dhive"; +import { ThreeSpeakVideo } from "./speak.types"; +import { decryptKey } from "../../utils/crypto"; +import hs from 'hivesigner'; const studioEndPoint = "https://studio.3speak.tv"; const tusEndPoint = "https://uploads.3speak.tv/files/"; const client = axios.create({}); -export const threespeakAuth = async (username: string) => { + + +export const threespeakAuth = async (currentAccount: any, pinHash: string) => { try { - let response = await client.get( - `${studioEndPoint}/mobile/login?username=${username}&hivesigner=true`, - { - withCredentials: false, - headers: { - "Content-Type": "application/json" - } - } - ); - const memo_string = response.data.memo; - let { memoDecoded } = await getDecodedMemo(username, memo_string); - - memoDecoded = memoDecoded.replace("#", ""); - return memoDecoded; + let response = await client.get( + `${studioEndPoint}/mobile/login?username=${currentAccount.username}&hivesigner=true`, + { + withCredentials: false, + headers: { + "Content-Type": "application/json" + } + } + ); + const memo_string = response.data.memo; + const memoDecoded = await getDecodedMemo(currentAccount.local, pinHash, memo_string); + + return memoDecoded.replace("#", ""); + } catch (err) { - console.error(new Error("[3Speak auth] Failed to login")); - throw err; + console.error(new Error("[3Speak auth] Failed to login")); + throw err; } - }; - - export const getTokenValidated = async (jwt: string, username: string) => { - try { - let response = await client.get( - `${studioEndPoint}/mobile/login?username=${username}&access_token=${jwt}`, - { - withCredentials: false, - headers: { - "Content-Type": "application/json" - } - } - ); - return response.data; - } catch (err) { - console.log(err); - throw err; - } - }; - - export const uploadVideoInfo = async ( +}; + + + +export const uploadVideoInfo = async ( + currentAccount: any, + pinHash: string, oFilename: string, fileSize: number, videoUrl: string, thumbnailUrl: string, username: string, duration: string - ) => { - const token = await threespeakAuth(username); +) => { + const token = await threespeakAuth(currentAccount, pinHash); try { - const { data } = await axios.post( - `${studioEndPoint}/mobile/api/upload_info?app=ecency`, - { - filename: videoUrl, - oFilename: oFilename, - size: fileSize, - duration, - thumbnail: thumbnailUrl, - isReel: false, - owner: username - }, - { - withCredentials: false, - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token}` - } - } - ); - return data; + const { data } = await axios.post( + `${studioEndPoint}/mobile/api/upload_info?app=ecency`, + { + filename: videoUrl, + oFilename: oFilename, + size: fileSize, + duration, + thumbnail: thumbnailUrl, + isReel: false, + owner: username + }, + { + withCredentials: false, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}` + } + } + ); + return data; } catch (e) { - console.error(e); - throw e; + console.error(e); + throw e; } - }; - - export const getAllVideoStatuses = async (username: string) => { - const token = await threespeakAuth(username); +}; + +export const getAllVideoStatuses = async (currentAccount: any, pinHash: string) => { + const token = await threespeakAuth(currentAccount, pinHash); try { - let response = await client.get(`${studioEndPoint}/mobile/api/my-videos`, { - withCredentials: false, - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token}` - } - }); - return response.data; + let response = await client.get(`${studioEndPoint}/mobile/api/my-videos`, { + withCredentials: false, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}` + } + }); + return response.data; } catch (err) { - console.error(new Error("[3Speak video] Failed to get videos")); - - throw err; + console.error(new Error("[3Speak video] Failed to get videos")); + + throw err; } - }; - - export const updateSpeakVideoInfo = async ( - username: string, +}; + +export const updateSpeakVideoInfo = async ( + currentAccount: any, + pinHash: string, postBody: string, videoId: string, title: string, tags: string[], isNsfwC: boolean - ) => { - const token = await threespeakAuth(username); - +) => { + const token = await threespeakAuth(currentAccount, pinHash); + const data = { - videoId: videoId, - title: title, - description: postBody, - isNsfwContent: isNsfwC, - tags_v2: tags + videoId: videoId, + title: title, + description: postBody, + isNsfwContent: isNsfwC, + tags_v2: tags }; - + const headers = { - "Content-Type": "application/json", - Authorization: `Bearer ${token}` + "Content-Type": "application/json", + Authorization: `Bearer ${token}` }; - + try { - await axios.post(`${studioEndPoint}/mobile/api/update_info`, data, { headers }); + await axios.post(`${studioEndPoint}/mobile/api/update_info`, data, { headers }); } catch (e) { - console.error(e); + console.error(e); } - }; - - export const markAsPublished = async (username: string, videoId: string) => { - const token = await threespeakAuth(username); +}; + +export const markAsPublished = async (currentAccount: any, pinHash: string, videoId: string) => { + const token = await threespeakAuth(currentAccount, pinHash); const data = { - videoId + videoId }; - + const headers = { - "Content-Type": "application/json", - Authorization: `Bearer ${token}` + "Content-Type": "application/json", + Authorization: `Bearer ${token}` }; - + axios - .post(`${studioEndPoint}/mobile/api/my-videos/iPublished`, data, { headers }) - .then((response) => {}) - .catch((error) => { - console.error("Error:", error); - }); - }; + .post(`${studioEndPoint}/mobile/api/my-videos/iPublished`, data, { headers }) + .then((response) => { }) + .catch((error) => { + console.error("Error:", error); + }); +}; - export const uploadVideo = async (media, onUploadProgress) => { +export const uploadVideo = async (media, onUploadProgress) => { try { - const file = { - uri: media.path, - type: media.mime, - name: media.filename || `img_${Math.random()}.mp4`, - size: media.size, - }; - - const fData = new FormData(); - fData.append('file', file); - - const res = await axios.post(tusEndPoint, fData, { - onUploadProgress - }); - if (!res || !res.data) { - throw new Error('Returning response missing media data'); - } - return res.data; + const file = { + uri: media.path, + type: media.mime, + name: media.filename || `img_${Math.random()}.mp4`, + size: media.size, + }; + + const fData = new FormData(); + fData.append('file', file); + + const res = await axios.post(tusEndPoint, fData, { + onUploadProgress + }); + if (!res || !res.data) { + throw new Error('Returning response missing media data'); + } + return res.data; } catch (error) { - console.warn('Image upload failed', error); - throw error; + console.warn('Image upload failed', error); + throw error; } - }; - +}; + // export const uploadFile = async ( // file: File, // type: string, @@ -188,7 +178,7 @@ export const threespeakAuth = async (username: string) => { // }>((resolve, reject) => { // let vPercentage = 0; // let tPercentage = 0; - + // const upload: any = new tus.Upload(file, { // endpoint: tusEndPoint, // retryDelays: [0, 3000, 5000, 10000, 20000], @@ -221,4 +211,27 @@ export const threespeakAuth = async (username: string) => { // upload.start(); // }); // }; - \ No newline at end of file + + +const getDecodedMemo = async (local, pinHash, encryptedMemo) => { + try { + const digitPinCode = getDigitPinCode(pinHash) + const token = decryptKey(local.accessToken, digitPinCode); + + const client = new hs.Client({ + accessToken: token, + }) + + const { memoDecoded } = await client.decode(encryptedMemo); + + if (!memoDecoded) { + throw new Error("Decode failed") + } + + return memoDecoded; + + } catch (err) { + console.warn("Failed to decode memo key", err) + } + +} \ No newline at end of file diff --git a/src/providers/speak/speak.types.ts b/src/providers/speak/speak.types.ts new file mode 100644 index 000000000..e801da805 --- /dev/null +++ b/src/providers/speak/speak.types.ts @@ -0,0 +1,3 @@ +export interface ThreeSpeakVideo { + +} \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index d2b1878c2..82279228c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5551,10 +5551,10 @@ hive-uri@^0.2.5: resolved "https://registry.yarnpkg.com/hive-uri/-/hive-uri-0.2.5.tgz#11f94d43b87d22c2a9c018e6ed41d303d3e0c770" integrity sha512-oSFqa39/Frs8XaA6oAT1W/5KtkInfp8u0Yv58YGok1klu7M8rPYMg3v9m/0rdvrRLSheAYwip88l60at2kPtYA== -hivesigner@^3.2.7: - version "3.2.9" - resolved "https://registry.yarnpkg.com/hivesigner/-/hivesigner-3.2.9.tgz#c0b670d7c47fe04516b8986fbe2c8b5f645eaaeb" - integrity sha512-VHJTW4FD6O8ZBdFWDkOLOnC2s5rjIOoDK9Pz4RK+mbs9/l1AyF2K6Z+bVZGzSluRsc7fjThweLg4EuPEVbEQYw== +hivesigner@^3.3.4: + version "3.3.4" + resolved "https://registry.yarnpkg.com/hivesigner/-/hivesigner-3.3.4.tgz#5ab19f25821eacb6683d86ee098e3868f028497e" + integrity sha512-n+fpsmc3FvkwXwhSTHJgChq97YeL2bEcJz/Awn9o+boFnIxqrxg4Y3i4sMMR8j+kJnwDV9c5JIMF4zQVxPSPJQ== dependencies: "@babel/runtime" "^7.13.9" cross-fetch "^3.0.6" From 4b57f35f840cd6b168748765a3f1c61958fc61da Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 19 Oct 2023 14:11:47 +0500 Subject: [PATCH 008/111] updated 3 spk video type --- src/providers/speak/speak.types.ts | 51 +++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/src/providers/speak/speak.types.ts b/src/providers/speak/speak.types.ts index e801da805..1777203c6 100644 --- a/src/providers/speak/speak.types.ts +++ b/src/providers/speak/speak.types.ts @@ -1,3 +1,52 @@ export interface ThreeSpeakVideo { - + app: string; + beneficiaries: string; // e.g. "[{\"account\":\"actifit-he\",\"weight\":100,\"src\":\"ENCODER_PAY\"}]" + category: string; + community: unknown | null; + created: string; // e.g. "2023-06-21T12:02:10.421Z" + declineRewards: boolean; + description: string; + donations: boolean; + duration: number; + encoding: Record; + encodingProgress: number; + encoding_price_steem: string; + filename: string; + firstUpload: boolean; + fromMobile: boolean; + height: unknown; + hive: string; + indexed: boolean; + is3CJContent: boolean; + isNsfwContent: boolean; + isReel: boolean; + isVOD: boolean; + job_id: string; + language: string; + local_filename: string; + lowRc: boolean; + needsBlockchainUpdate: boolean; + originalFilename: string; + owner: string; + paid: boolean; + permlink: string; + postToHiveBlog: boolean; + publish_type: string; + reducedUpvote: boolean; + rewardPowerup: boolean; + size: number; + status: string; + tags_v2: unknown[]; + thumbUrl: string; + thumbnail: string; + title: string; + updateSteem: boolean; + upload_type: string; + upvoteEligible: boolean; + video_v2: string; + views: number; + votePercent: number; + width: unknown; + __v: number; + _id: string; } \ No newline at end of file From a66aadc208b4b58cb0719fbea0ad6d7379392ebe Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 19 Oct 2023 17:17:58 +0500 Subject: [PATCH 009/111] insert video toolbar button --- .../markdownEditor/children/editorToolbar.tsx | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/components/markdownEditor/children/editorToolbar.tsx b/src/components/markdownEditor/children/editorToolbar.tsx index affb941fc..f27e88d13 100644 --- a/src/components/markdownEditor/children/editorToolbar.tsx +++ b/src/components/markdownEditor/children/editorToolbar.tsx @@ -45,8 +45,8 @@ export const EditorToolbar = ({ const shouldHideExtension = useRef(false); const extensionHeight = useRef(0); - const [isExtensionVisible, setIsExtensionVisible] = useState(false); - + const [isExtensionVisible, setIsExtensionVisible] = useState(false); + const [isKeyboardVisible, setKeyboardVisible] = useState(false); useEffect(() => { @@ -246,6 +246,7 @@ export const EditorToolbar = ({ iconType="MaterialCommunityIcons" name="text-short" /> + + { From c829a643305154ddb72d67306d2e07a0e20437f2 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Thu, 19 Oct 2023 19:02:32 +0500 Subject: [PATCH 010/111] converting speak video to ecency media item object --- src/providers/speak/converters.ts | 12 ++++++++++++ src/providers/speak/speak.ts | 6 +++++- 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 src/providers/speak/converters.ts diff --git a/src/providers/speak/converters.ts b/src/providers/speak/converters.ts new file mode 100644 index 000000000..937cdb7b7 --- /dev/null +++ b/src/providers/speak/converters.ts @@ -0,0 +1,12 @@ +import { MediaItem } from "../ecency/ecency.types" + + +export const convertVideoUpload = (videoItem) => { + return { + _id:videoItem._id, + url:videoItem._id, //TOOD: add a better url or change prop + thumbUrl:videoItem.thumbUrl, + created:videoItem.created, + timestamp:0 + } as MediaItem +} \ No newline at end of file diff --git a/src/providers/speak/speak.ts b/src/providers/speak/speak.ts index d5c67dc83..92fdba136 100644 --- a/src/providers/speak/speak.ts +++ b/src/providers/speak/speak.ts @@ -3,6 +3,7 @@ import { getDigitPinCode } from "../hive/dhive"; import { ThreeSpeakVideo } from "./speak.types"; import { decryptKey } from "../../utils/crypto"; import hs from 'hivesigner'; +import { convertVideoUpload } from "./converters"; const studioEndPoint = "https://studio.3speak.tv"; const tusEndPoint = "https://uploads.3speak.tv/files/"; @@ -82,7 +83,10 @@ export const getAllVideoStatuses = async (currentAccount: any, pinHash: string) Authorization: `Bearer ${token}` } }); - return response.data; + + const mediaItems = response.data.map(convertVideoUpload); + + return mediaItems; } catch (err) { console.error(new Error("[3Speak video] Failed to get videos")); From b0be1d312a108189c86d02f13e8166a3439266e1 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Thu, 19 Oct 2023 19:02:40 +0500 Subject: [PATCH 011/111] converting speak video to ecency media item object --- src/providers/ecency/ecency.types.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/providers/ecency/ecency.types.ts b/src/providers/ecency/ecency.types.ts index ce6ced264..1e8c202d6 100644 --- a/src/providers/ecency/ecency.types.ts +++ b/src/providers/ecency/ecency.types.ts @@ -10,6 +10,7 @@ export interface ReceivedVestingShare { export interface MediaItem { _id: string; url: string; + thumbUrl: string; created: string; timestamp: number; } From b3457771debff73cb4b33e16969bd8ae9cb925d2 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Thu, 19 Oct 2023 19:03:16 +0500 Subject: [PATCH 012/111] added query to track video uploads --- src/providers/queries/editorQueries.ts | 20 ++++++++++++++++++++ src/providers/queries/queryKeys.ts | 1 + 2 files changed, 21 insertions(+) diff --git a/src/providers/queries/editorQueries.ts b/src/providers/queries/editorQueries.ts index 11ed9c552..39b9a8f25 100644 --- a/src/providers/queries/editorQueries.ts +++ b/src/providers/queries/editorQueries.ts @@ -19,6 +19,8 @@ import QUERIES from './queryKeys'; import Upload, { UploadOptions } from 'react-native-background-upload' import Config from 'react-native-config'; import { Platform } from 'react-native'; +import { getAllVideoStatuses } from '../speak/speak'; +import { ThreeSpeakVideo } from '../speak/speak.types'; interface SnippetMutationVars { id: string | null; @@ -78,6 +80,24 @@ export const useAddToUploadsMutation = () => { }); }; + +export const useVideoUploadsQuery = () => { + const intl = useIntl(); + const dispatch = useAppDispatch(); + + const currentAccount = useAppSelector(state => state.account.currentAccount); + const pinHash = useAppSelector(state => state.application.pin); + + const _fetchVideoUploads = async () => await getAllVideoStatuses(currentAccount, pinHash); + + return useQuery([QUERIES.MEDIA.GET_VIDEOS], _fetchVideoUploads, { + initialData: [], + onError: () => { + dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); + }, + }); +} + export const useMediaUploadMutation = () => { const intl = useIntl(); const dispatch = useAppDispatch(); diff --git a/src/providers/queries/queryKeys.ts b/src/providers/queries/queryKeys.ts index 925c229c3..9d97a381d 100644 --- a/src/providers/queries/queryKeys.ts +++ b/src/providers/queries/queryKeys.ts @@ -13,6 +13,7 @@ const QUERIES = { }, MEDIA: { GET: 'QUERY_GET_UPLOADS', + GET_VIDEOS: 'QUERY_GET_VIDEO_UPLOADS' }, WALLET: { GET: 'QUERY_GET_ASSETS', From c18f0ff202e81b832dbc909b245ff4262bcaebf0 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Thu, 19 Oct 2023 19:03:48 +0500 Subject: [PATCH 013/111] support for video and images mode in gallery modal --- .../markdownEditor/children/editorToolbar.tsx | 19 ++++++-- .../children/uploadsGalleryContent.tsx | 8 ++-- .../container/uploadsGalleryModal.tsx | 48 ++++++++++++++----- 3 files changed, 54 insertions(+), 21 deletions(-) diff --git a/src/components/markdownEditor/children/editorToolbar.tsx b/src/components/markdownEditor/children/editorToolbar.tsx index f27e88d13..91c0fb2f9 100644 --- a/src/components/markdownEditor/children/editorToolbar.tsx +++ b/src/components/markdownEditor/children/editorToolbar.tsx @@ -11,7 +11,7 @@ import Animated, { EasingNode, Extrapolate } from 'react-native-reanimated'; import { IconButton, UploadsGalleryModal } from '../..'; import styles from '../styles/editorToolbarStyles'; import { useAppSelector } from '../../../hooks'; -import { MediaInsertData } from '../../uploadsGalleryModal/container/uploadsGalleryModal'; +import { MediaInsertData, Modes } from '../../uploadsGalleryModal/container/uploadsGalleryModal'; import Formats from './formats/formats'; type Props = { @@ -81,15 +81,24 @@ export const EditorToolbar = ({ ); - const _showUploadsExtension = () => { + + const _showUploadsExtension = (mode:Modes) => { if (isExtensionVisible && uploadsGalleryModalRef.current) { _hideExtension(); } else if (uploadsGalleryModalRef.current) { - uploadsGalleryModalRef.current.toggleModal(true); + uploadsGalleryModalRef.current.toggleModal(true, mode); _revealExtension(); } }; + const _showImageUploads = () => { + _showUploadsExtension(Modes.MODE_IMAGE) + } + + const _showVideoUploads = () => { + _showUploadsExtension(Modes.MODE_VIDEO) + } + // handles extension closing const _onGestureEvent = Animated.event( [ @@ -248,7 +257,7 @@ export const EditorToolbar = ({ /> ) => void; handleOpenGallery: (addToUploads?: boolean) => void; @@ -101,7 +101,7 @@ const UploadsGalleryContent = ({ }; // render list item for snippet and handle actions; - const _renderItem = ({ item, index }: { item: UploadedMedia; index: number }) => { + const _renderItem = ({ item, index }: { item: MediaItem; index: number }) => { const _onPress = () => { if (isDeleteMode) { const idIndex = deleteIds.indexOf(item._id); @@ -116,7 +116,7 @@ const UploadsGalleryContent = ({ } }; - const thumbUrl = proxifyImageSrc(item.url, 600, 500, Platform.OS === 'ios' ? 'match' : 'webp'); + const thumbUrl = item.thumbUrl || proxifyImageSrc(item.url, 600, 500, Platform.OS === 'ios' ? 'match' : 'webp'); let isInsertedTimes = 0; insertedMediaUrls?.forEach((url) => (isInsertedTimes += url === item.url ? 1 : 0)); const isToBeDeleted = deleteIds.indexOf(item._id) >= 0; diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index d7f5bcf71..4afbef9ac 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -11,7 +11,7 @@ import UploadsGalleryContent from '../children/uploadsGalleryContent'; import { useAppDispatch, useAppSelector } from '../../../hooks'; import { delay, extractFilenameFromPath } from '../../../utils/editor'; import showLoginAlert from '../../../utils/showLoginAlert'; -import { useMediaQuery, useMediaUploadMutation } from '../../../providers/queries'; +import { useMediaQuery, useMediaUploadMutation, useVideoUploadsQuery } from '../../../providers/queries'; import { showActionModal } from '../../../redux/actions/uiAction'; export interface UploadsGalleryModalRef { @@ -31,6 +31,11 @@ export interface MediaInsertData { status: MediaInsertStatus; } +export enum Modes { + MODE_IMAGE = 0, + MODE_VIDEO = 1 +} + interface UploadsGalleryModalProps { insertedMediaUrls: string[]; paramFiles: any[]; @@ -62,6 +67,7 @@ export const UploadsGalleryModal = forwardRef( const dispatch = useAppDispatch(); const mediaQuery = useMediaQuery(); + const videoUploads = useVideoUploadsQuery(); const mediaUploadMutation = useMediaUploadMutation(); const pendingInserts = useRef([]); @@ -69,13 +75,16 @@ export const UploadsGalleryModal = forwardRef( const [mediaUploads, setMediaUploads] = useState([]); const [showModal, setShowModal] = useState(false); const [isAddingToUploads, setIsAddingToUploads] = useState(false); + const [mode, setMode] = useState(Modes.MODE_IMAGE) const isLoggedIn = useAppSelector((state) => state.application.isLoggedIn); + + const pinCode = useAppSelector((state) => state.application.pin); const currentAccount = useAppSelector((state) => state.account.currentAccount); useImperativeHandle(ref, () => ({ - toggleModal: (value: boolean) => { + toggleModal: (value: boolean, _mode: Modes) => { if (!isLoggedIn) { showLoginAlert({ intl }); return; @@ -86,9 +95,12 @@ export const UploadsGalleryModal = forwardRef( } if (value) { - _getMediaUploads(); + _getMediaUploads(_mode); } + + setMode(_mode) setShowModal(value); + }, })); @@ -116,6 +128,8 @@ export const UploadsGalleryModal = forwardRef( } }, [paramFiles]); + + useEffect(() => { if (!isEditing && pendingInserts.current.length) { handleMediaInsert(pendingInserts.current); @@ -124,8 +138,8 @@ export const UploadsGalleryModal = forwardRef( }, [isEditing]); useEffect(() => { - _getMediaUploads(); // get media uploads when there is new update - }, [mediaQuery.data]); + _getMediaUploads(mode); // get media uploads when there is new update + }, [mediaQuery.data, videoUploads.data, mode]); const _handleOpenImagePicker = (addToUploads?: boolean) => { ImagePicker.openPicker({ @@ -347,14 +361,22 @@ export const UploadsGalleryModal = forwardRef( }; // fetch images from server - const _getMediaUploads = async () => { + const _getMediaUploads = async (_mode: Modes = mode) => { try { - if (username) { - console.log(`getting images for: ${username}`); - const images = await getImages(); - console.log('images received', images); - setMediaUploads(images || []); + + if (_mode === Modes.MODE_VIDEO) { + videoUploads.refetch(); + } else { + if (_mode === Modes.MODE_IMAGE) { + if (username) { + console.log(`getting images for: ${username}`); + const images = await getImages(); + console.log('images received', images); + setMediaUploads(images || []); + } + } } + } catch (err) { console.warn('Failed to get images'); } @@ -376,12 +398,14 @@ export const UploadsGalleryModal = forwardRef( handleMediaInsert(data); }; + const data = mode === Modes.MODE_VIDEO ? videoUploads.data.slice() : mediaQuery.data.slice() + return ( !isPreviewActive && showModal && ( Date: Thu, 19 Oct 2023 19:17:17 +0500 Subject: [PATCH 014/111] united media query, inserting video id --- .../children/formats/applyMediaLink.ts | 7 +-- .../container/uploadsGalleryModal.tsx | 48 +++++++++---------- 2 files changed, 26 insertions(+), 29 deletions(-) diff --git a/src/components/markdownEditor/children/formats/applyMediaLink.ts b/src/components/markdownEditor/children/formats/applyMediaLink.ts index f8be9a6de..cc99ba475 100644 --- a/src/components/markdownEditor/children/formats/applyMediaLink.ts +++ b/src/components/markdownEditor/children/formats/applyMediaLink.ts @@ -1,6 +1,7 @@ import { MediaInsertData, MediaInsertStatus, + Modes, } from '../../../uploadsGalleryModal/container/uploadsGalleryModal'; import { replaceBetween } from './utils'; @@ -28,8 +29,8 @@ export default async ({ text, selection, setTextAndSelection, items }: Args) => let newText = text; let newSelection = selection; - const _insertFormatedString = (text, value) => { - const formatedText = `\n${imagePrefix}[${text}](${value})\n`; + const _insertFormatedString = (text, value, mode) => { + const formatedText = `\n${ mode === Modes.MODE_VIDEO ? '' : imagePrefix}[${text}](${value})\n`; newText = replaceBetween(newText, newSelection, formatedText); const newIndex = newText && newText.indexOf(value, newSelection.start) + value.length + 2; newSelection = { @@ -80,7 +81,7 @@ export default async ({ text, selection, setTextAndSelection, items }: Args) => // means placeholder is preset is needs replacing _replaceFormatedString(_placeholder, item.url); } else if (item.url) { - _insertFormatedString(item.text, item.url); + _insertFormatedString(item.text, item.url, item.mode); } break; diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 4afbef9ac..ed315e427 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -1,11 +1,10 @@ -import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'; +import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'; import { useIntl } from 'react-intl'; import { Alert, AlertButton } from 'react-native'; import ImagePicker, { Image } from 'react-native-image-crop-picker'; import RNHeicConverter from 'react-native-heic-converter'; import { openSettings } from 'react-native-permissions'; import bugsnapInstance from '../../../config/bugsnag'; -import { getImages } from '../../../providers/ecency/ecency'; import UploadsGalleryContent from '../children/uploadsGalleryContent'; import { useAppDispatch, useAppSelector } from '../../../hooks'; @@ -18,6 +17,12 @@ export interface UploadsGalleryModalRef { showModal: () => void; } + +export enum Modes { + MODE_IMAGE = 0, + MODE_VIDEO = 1 +} + export enum MediaInsertStatus { UPLOADING = 'UPLOADING', READY = 'READY', @@ -29,12 +34,10 @@ export interface MediaInsertData { filename?: string; text: string; status: MediaInsertStatus; + mode: Modes; } -export enum Modes { - MODE_IMAGE = 0, - MODE_VIDEO = 1 -} + interface UploadsGalleryModalProps { insertedMediaUrls: string[]; @@ -66,19 +69,24 @@ export const UploadsGalleryModal = forwardRef( const intl = useIntl(); const dispatch = useAppDispatch(); - const mediaQuery = useMediaQuery(); - const videoUploads = useVideoUploadsQuery(); + const imageUploadsQuery = useMediaQuery(); + const videoUploadsQuery = useVideoUploadsQuery(); + + + const mediaUploadMutation = useMediaUploadMutation(); const pendingInserts = useRef([]); - const [mediaUploads, setMediaUploads] = useState([]); const [showModal, setShowModal] = useState(false); const [isAddingToUploads, setIsAddingToUploads] = useState(false); const [mode, setMode] = useState(Modes.MODE_IMAGE) const isLoggedIn = useAppSelector((state) => state.application.isLoggedIn); + const mediaUploadsQuery = useMemo( + ()=> mode === Modes.MODE_VIDEO ? videoUploadsQuery : imageUploadsQuery , [mode]) + const pinCode = useAppSelector((state) => state.application.pin); const currentAccount = useAppSelector((state) => state.account.currentAccount); @@ -139,7 +147,7 @@ export const UploadsGalleryModal = forwardRef( useEffect(() => { _getMediaUploads(mode); // get media uploads when there is new update - }, [mediaQuery.data, videoUploads.data, mode]); + }, [mediaUploadsQuery.data, mode]); const _handleOpenImagePicker = (addToUploads?: boolean) => { ImagePicker.openPicker({ @@ -363,19 +371,7 @@ export const UploadsGalleryModal = forwardRef( // fetch images from server const _getMediaUploads = async (_mode: Modes = mode) => { try { - - if (_mode === Modes.MODE_VIDEO) { - videoUploads.refetch(); - } else { - if (_mode === Modes.MODE_IMAGE) { - if (username) { - console.log(`getting images for: ${username}`); - const images = await getImages(); - console.log('images received', images); - setMediaUploads(images || []); - } - } - } + mediaUploadsQuery.refetch(); } catch (err) { console.warn('Failed to get images'); @@ -388,17 +384,17 @@ export const UploadsGalleryModal = forwardRef( const data: MediaInsertData[] = []; for (const index of map.keys()) { console.log(index); - const item = mediaUploads[index]; + const item = mediaUploadsQuery.data[index]; data.push({ url: item.url, - text: '', + text: mode === Modes.MODE_VIDEO ? '3speak' : '', status: MediaInsertStatus.READY, }); } handleMediaInsert(data); }; - const data = mode === Modes.MODE_VIDEO ? videoUploads.data.slice() : mediaQuery.data.slice() + const data = mediaUploadsQuery.data.slice(); return ( !isPreviewActive && From dcfae845ad2cc4cc969b3674fe8a75bb40d3e575 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 19 Oct 2023 23:07:35 +0500 Subject: [PATCH 015/111] successfylly insert both videos and images using single media modal --- .../uploadsGalleryModal/container/uploadsGalleryModal.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index ed315e427..1efd42850 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -389,6 +389,7 @@ export const UploadsGalleryModal = forwardRef( url: item.url, text: mode === Modes.MODE_VIDEO ? '3speak' : '', status: MediaInsertStatus.READY, + mode }); } handleMediaInsert(data); From bac822c944a94c1ff49a4e28326310f13d0e26b6 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 19 Oct 2023 23:25:04 +0500 Subject: [PATCH 016/111] switching between video and image modes with single tap --- .../markdownEditor/children/editorToolbar.tsx | 15 ++++++++++++--- .../container/uploadsGalleryModal.tsx | 5 +++-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/components/markdownEditor/children/editorToolbar.tsx b/src/components/markdownEditor/children/editorToolbar.tsx index 91c0fb2f9..60d53aab0 100644 --- a/src/components/markdownEditor/children/editorToolbar.tsx +++ b/src/components/markdownEditor/children/editorToolbar.tsx @@ -83,12 +83,21 @@ export const EditorToolbar = ({ const _showUploadsExtension = (mode:Modes) => { - if (isExtensionVisible && uploadsGalleryModalRef.current) { - _hideExtension(); - } else if (uploadsGalleryModalRef.current) { + + if(!uploadsGalleryModalRef.current){ + return; + } + + const _curMode = uploadsGalleryModalRef.current.getMode(); + + if (!isExtensionVisible || _curMode !== mode){ uploadsGalleryModalRef.current.toggleModal(true, mode); _revealExtension(); + return; } + + _hideExtension() + }; const _showImageUploads = () => { diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 1efd42850..b9183205e 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -92,13 +92,13 @@ export const UploadsGalleryModal = forwardRef( const currentAccount = useAppSelector((state) => state.account.currentAccount); useImperativeHandle(ref, () => ({ - toggleModal: (value: boolean, _mode: Modes) => { + toggleModal: (value: boolean, _mode: Modes = mode) => { if (!isLoggedIn) { showLoginAlert({ intl }); return; } - if (value === showModal) { + if (value === showModal && _mode === mode) { return; } @@ -110,6 +110,7 @@ export const UploadsGalleryModal = forwardRef( setShowModal(value); }, + getMode: () => mode, })); useEffect(() => { From 2ec7bad3f924a5a09381a06ac618cf228ee0bc8b Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Fri, 20 Oct 2023 19:57:01 +0500 Subject: [PATCH 017/111] generating speak vidoe url in converter --- src/providers/speak/constants.ts | 11 +++++++++++ src/providers/speak/converters.ts | 11 ++++++----- src/providers/speak/speak.ts | 20 ++++++++++++-------- 3 files changed, 29 insertions(+), 13 deletions(-) create mode 100644 src/providers/speak/constants.ts diff --git a/src/providers/speak/constants.ts b/src/providers/speak/constants.ts new file mode 100644 index 000000000..9d4f8c209 --- /dev/null +++ b/src/providers/speak/constants.ts @@ -0,0 +1,11 @@ + +export const BASE_URL_SPEAK_STUDIO = "https://studio.3speak.tv"; + +export const BASE_URL_SPEAK_UPLOAD = "https://uploads.3speak.tv/files"; + +export const BASE_URL_SPEAK_WATCH = "https://3speak.tv/watch"; + + +export const PATH_MOBILE = "mobile"; +export const PATH_LOGIN = "login"; +export const PATH_API = "api"; diff --git a/src/providers/speak/converters.ts b/src/providers/speak/converters.ts index 937cdb7b7..de9aca309 100644 --- a/src/providers/speak/converters.ts +++ b/src/providers/speak/converters.ts @@ -1,12 +1,13 @@ import { MediaItem } from "../ecency/ecency.types" +import { BASE_URL_SPEAK_WATCH } from "./constants" -export const convertVideoUpload = (videoItem) => { +export const convertVideoUpload = (data) => { return { - _id:videoItem._id, - url:videoItem._id, //TOOD: add a better url or change prop - thumbUrl:videoItem.thumbUrl, - created:videoItem.created, + _id:data._id, + url:`${BASE_URL_SPEAK_WATCH}?v=${data.owner}/${data.permlink}`, + thumbUrl:data.thumbUrl, + created:data.created, timestamp:0 } as MediaItem } \ No newline at end of file diff --git a/src/providers/speak/speak.ts b/src/providers/speak/speak.ts index 92fdba136..6285b9157 100644 --- a/src/providers/speak/speak.ts +++ b/src/providers/speak/speak.ts @@ -4,17 +4,21 @@ import { ThreeSpeakVideo } from "./speak.types"; import { decryptKey } from "../../utils/crypto"; import hs from 'hivesigner'; import { convertVideoUpload } from "./converters"; +import { BASE_URL_SPEAK_STUDIO, PATH_API, PATH_LOGIN, PATH_MOBILE } from "./constants"; -const studioEndPoint = "https://studio.3speak.tv"; const tusEndPoint = "https://uploads.3speak.tv/files/"; -const client = axios.create({}); + + +const speakApi = axios.create({ + baseURL:`${BASE_URL_SPEAK_STUDIO}/${PATH_MOBILE}` +}); export const threespeakAuth = async (currentAccount: any, pinHash: string) => { try { - let response = await client.get( - `${studioEndPoint}/mobile/login?username=${currentAccount.username}&hivesigner=true`, + let response = await speakApi.get( + `${PATH_LOGIN}?username=${currentAccount.username}&hivesigner=true`, { withCredentials: false, headers: { @@ -48,7 +52,7 @@ export const uploadVideoInfo = async ( const token = await threespeakAuth(currentAccount, pinHash); try { const { data } = await axios.post( - `${studioEndPoint}/mobile/api/upload_info?app=ecency`, + `${PATH_API}/upload_info?app=ecency`, { filename: videoUrl, oFilename: oFilename, @@ -76,7 +80,7 @@ export const uploadVideoInfo = async ( export const getAllVideoStatuses = async (currentAccount: any, pinHash: string) => { const token = await threespeakAuth(currentAccount, pinHash); try { - let response = await client.get(`${studioEndPoint}/mobile/api/my-videos`, { + let response = await speakApi.get(`${PATH_API}/my-videos`, { withCredentials: false, headers: { "Content-Type": "application/json", @@ -119,7 +123,7 @@ export const updateSpeakVideoInfo = async ( }; try { - await axios.post(`${studioEndPoint}/mobile/api/update_info`, data, { headers }); + await axios.post(`${PATH_API}/update_info`, data, { headers }); } catch (e) { console.error(e); } @@ -137,7 +141,7 @@ export const markAsPublished = async (currentAccount: any, pinHash: string, vide }; axios - .post(`${studioEndPoint}/mobile/api/my-videos/iPublished`, data, { headers }) + .post(`${PATH_API}/my-videos/iPublished`, data, { headers }) .then((response) => { }) .catch((error) => { console.error("Error:", error); From 3ae24d27a584ebcbca01ff692d4e8a5f8bf4f649 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Fri, 20 Oct 2023 19:57:36 +0500 Subject: [PATCH 018/111] inserting formatted video link in editor --- .../markdownEditor/children/formats/applyMediaLink.ts | 5 ++++- .../uploadsGalleryModal/container/uploadsGalleryModal.tsx | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/components/markdownEditor/children/formats/applyMediaLink.ts b/src/components/markdownEditor/children/formats/applyMediaLink.ts index cc99ba475..be29ee6c8 100644 --- a/src/components/markdownEditor/children/formats/applyMediaLink.ts +++ b/src/components/markdownEditor/children/formats/applyMediaLink.ts @@ -24,13 +24,16 @@ export default async ({ text, selection, setTextAndSelection, items }: Args) => // calclulate change of cursor position const imagePrefix = '!'; + const videoPrefix = '
'; + const videoPostfix = '
'; + const placeholderPrefix = 'Uploading... '; let newText = text; let newSelection = selection; const _insertFormatedString = (text, value, mode) => { - const formatedText = `\n${ mode === Modes.MODE_VIDEO ? '' : imagePrefix}[${text}](${value})\n`; + const formatedText = `\n${ mode === Modes.MODE_VIDEO ? videoPrefix : imagePrefix}[${text}](${value})${mode === Modes.MODE_VIDEO ? videoPostfix : ''}\n`; newText = replaceBetween(newText, newSelection, formatedText); const newIndex = newText && newText.indexOf(value, newSelection.start) + value.length + 2; newSelection = { diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index b9183205e..9e72dfb74 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -388,7 +388,7 @@ export const UploadsGalleryModal = forwardRef( const item = mediaUploadsQuery.data[index]; data.push({ url: item.url, - text: mode === Modes.MODE_VIDEO ? '3speak' : '', + text: mode === Modes.MODE_VIDEO ? `![](${item.thumbUrl})` : '', status: MediaInsertStatus.READY, mode }); From 2cf93878b22b6f454d24598e60ddb5a7df029f78 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 27 Oct 2023 00:34:12 +0500 Subject: [PATCH 019/111] support for extracting meta for speak video --- src/utils/editor.ts | 46 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/src/utils/editor.ts b/src/utils/editor.ts index aefc704d0..31351b853 100644 --- a/src/utils/editor.ts +++ b/src/utils/editor.ts @@ -4,6 +4,7 @@ import { diff_match_patch as diffMatchPatch } from 'diff-match-patch'; import VersionNumber from 'react-native-version-number'; import MimeTypes from 'mime-types'; import { PostTypes } from '../constants/postTypes'; +import { ThreeSpeakVideo } from '../providers/speak/speak.types'; export const getWordsCount = (text) => text && typeof text === 'string' ? text.replace(/^\s+|\s+$/g, '').split(/\s+/).length : 0; @@ -216,16 +217,22 @@ export const extractMetadata = async ({ thumbUrl, fetchRatios, postType, + threeSpeakMeta }: { body: string; thumbUrl?: string; fetchRatios?: boolean; postType?: PostTypes; + threeSpeakMeta?: { + title:string, + description:string, + rawData:ThreeSpeakVideo + } }) => { // NOTE: keepting regex to extract usernames as reference for later usage if any // const userReg = /(^|\s)(@[a-z][-.a-z\d]+[a-z\d])/gim; - const out = {}; + const out:any = {}; const mUrls = extractUrls(body); const matchedImages = extractImageUrls({ urls: mUrls }); @@ -257,6 +264,43 @@ export const extractMetadata = async ({ ); } + if (threeSpeakMeta) { + const videoMetadata = threeSpeakMeta.rawData; + out.video = { + info: { + platform: "3speak", + title: threeSpeakMeta.title || videoMetadata.title, + author: videoMetadata.owner, + permlink: videoMetadata.permlink, + duration: videoMetadata.duration, + filesize: videoMetadata.size, + file: videoMetadata.filename, + lang: videoMetadata.language, + firstUpload: videoMetadata.firstUpload, + ipfs: null, + ipfsThumbnail: null, + video_v2: videoMetadata.video_v2, + sourceMap: [ + { + type: "video", + url: videoMetadata.video_v2, + format: "m3u8" + }, + { + type: "thumbnail", + url: videoMetadata.thumbUrl + } + ] + }, + content: { + description: threeSpeakMeta.description || videoMetadata.description, + tags: videoMetadata.tags_v2 + } + }; + } + + + //setting post type, primary usecase for separating waves from other posts out.type = postType || PostTypes.POST From d45d223812159cd8b3403caba91b5f81f730b807 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Wed, 1 Nov 2023 15:32:35 +0500 Subject: [PATCH 020/111] react query devtools integration --- package.json | 1 + src/index.tsx | 6 ++++++ yarn.lock | 12 ++++++++++++ 3 files changed, 19 insertions(+) diff --git a/package.json b/package.json index 9ef146c4e..d4e9fefb7 100644 --- a/package.json +++ b/package.json @@ -203,6 +203,7 @@ "eslint-plugin-react": "^7.13.0", "eslint-plugin-react-hooks": "^2.3.0", "eslint-plugin-react-native": "^3.7.0", + "react-query-native-devtools": "^4.0.0", "husky": "^3.1.0", "jest": "^26.6.3", "lint-staged": "^7.2.0", diff --git a/src/index.tsx b/src/index.tsx index cf2447108..d0b62ab38 100755 --- a/src/index.tsx +++ b/src/index.tsx @@ -15,6 +15,12 @@ import { initQueryClient } from './providers/queries'; const queryClientProviderProps = initQueryClient(); +if (__DEV__) { + import('react-query-native-devtools').then(({ addPlugin }) => { + addPlugin({ queryClient:queryClientProviderProps.client }); + }); +} + const _renderApp = ({ locale }) => ( diff --git a/yarn.lock b/yarn.lock index 82279228c..fe69b96b8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5073,6 +5073,11 @@ flatted@^3.1.0: resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.7.tgz#609f39207cb614b89d0765b477cb2d437fbf9787" integrity sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ== +flatted@^3.2.4: + version "3.2.9" + resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.9.tgz#7eb4c67ca1ba34232ca9d2d93e9886e611ad7daf" + integrity sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ== + flow-parser@0.*: version "0.201.0" resolved "https://registry.yarnpkg.com/flow-parser/-/flow-parser-0.201.0.tgz#d2005d4dae6fddf60d30f9ae0fb49a13c9c51cfe" @@ -9472,6 +9477,13 @@ react-navigation-redux-helpers@^4.0.1: dependencies: invariant "^2.2.2" +react-query-native-devtools@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/react-query-native-devtools/-/react-query-native-devtools-4.0.0.tgz#97d484d024503d484652f6e64a07c188f99ae702" + integrity sha512-TKwYO0tcw744c2aI1AGL2zoLycx3mr6Apl/3p9EIxh204kWGBpF7OhPQY7OKSdPvgw1jG6wlKzfAj3asgCSZGg== + dependencies: + flatted "^3.2.4" + react-redux@^8.0.4: version "8.0.5" resolved "https://registry.yarnpkg.com/react-redux/-/react-redux-8.0.5.tgz#e5fb8331993a019b8aaf2e167a93d10af469c7bd" From 95eaf7c1fa8bcb9c06a8f1a7d1166ccde2b3584c Mon Sep 17 00:00:00 2001 From: noumantahir Date: Wed, 1 Nov 2023 15:33:21 +0500 Subject: [PATCH 021/111] speakData in mediaItem support --- src/providers/ecency/ecency.types.ts | 2 ++ src/providers/speak/converters.ts | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/providers/ecency/ecency.types.ts b/src/providers/ecency/ecency.types.ts index 1e8c202d6..a534f6aef 100644 --- a/src/providers/ecency/ecency.types.ts +++ b/src/providers/ecency/ecency.types.ts @@ -1,4 +1,5 @@ import { QuoteItem } from '../../redux/reducers/walletReducer'; +import { ThreeSpeakVideo } from '../speak/speak.types'; export interface ReceivedVestingShare { delegator: string; @@ -13,6 +14,7 @@ export interface MediaItem { thumbUrl: string; created: string; timestamp: number; + speakData?:ThreeSpeakVideo } export interface Snippet { diff --git a/src/providers/speak/converters.ts b/src/providers/speak/converters.ts index de9aca309..208294f6c 100644 --- a/src/providers/speak/converters.ts +++ b/src/providers/speak/converters.ts @@ -8,6 +8,7 @@ export const convertVideoUpload = (data) => { url:`${BASE_URL_SPEAK_WATCH}?v=${data.owner}/${data.permlink}`, thumbUrl:data.thumbUrl, created:data.created, - timestamp:0 + timestamp:0, + speakData:data } as MediaItem } \ No newline at end of file From 877fbf75dfc0a3796d739ce5c394a84a316dc7c5 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Wed, 1 Nov 2023 15:34:05 +0500 Subject: [PATCH 022/111] following web format for inserting speak video --- .../markdownEditor/children/formats/applyMediaLink.ts | 5 ++--- .../uploadsGalleryModal/container/uploadsGalleryModal.tsx | 7 ++++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/components/markdownEditor/children/formats/applyMediaLink.ts b/src/components/markdownEditor/children/formats/applyMediaLink.ts index be29ee6c8..37bff963b 100644 --- a/src/components/markdownEditor/children/formats/applyMediaLink.ts +++ b/src/components/markdownEditor/children/formats/applyMediaLink.ts @@ -24,8 +24,7 @@ export default async ({ text, selection, setTextAndSelection, items }: Args) => // calclulate change of cursor position const imagePrefix = '!'; - const videoPrefix = '
'; - const videoPostfix = '
'; + const placeholderPrefix = 'Uploading... '; @@ -33,7 +32,7 @@ export default async ({ text, selection, setTextAndSelection, items }: Args) => let newSelection = selection; const _insertFormatedString = (text, value, mode) => { - const formatedText = `\n${ mode === Modes.MODE_VIDEO ? videoPrefix : imagePrefix}[${text}](${value})${mode === Modes.MODE_VIDEO ? videoPostfix : ''}\n`; + const formatedText = `\n${mode === Modes.MODE_VIDEO ? '' : imagePrefix}[${text}](${value})\n`; newText = replaceBetween(newText, newSelection, formatedText); const newIndex = newText && newText.indexOf(value, newSelection.start) + value.length + 2; newSelection = { diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 9e72dfb74..861d368e6 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -12,6 +12,7 @@ import { delay, extractFilenameFromPath } from '../../../utils/editor'; import showLoginAlert from '../../../utils/showLoginAlert'; import { useMediaQuery, useMediaUploadMutation, useVideoUploadsQuery } from '../../../providers/queries'; import { showActionModal } from '../../../redux/actions/uiAction'; +import { MediaItem } from '../../../providers/ecency/ecency.types'; export interface UploadsGalleryModalRef { showModal: () => void; @@ -385,10 +386,10 @@ export const UploadsGalleryModal = forwardRef( const data: MediaInsertData[] = []; for (const index of map.keys()) { console.log(index); - const item = mediaUploadsQuery.data[index]; + const item:MediaItem = mediaUploadsQuery.data[index]; data.push({ - url: item.url, - text: mode === Modes.MODE_VIDEO ? `![](${item.thumbUrl})` : '', + url: mode === Modes.MODE_VIDEO ? (item.speakData?._id || '') : item.url, + text: mode === Modes.MODE_VIDEO ? `3speak` : '', status: MediaInsertStatus.READY, mode }); From 2dcbc54539e99b5653ae40f8631466d011d72ccc Mon Sep 17 00:00:00 2001 From: Sadaqat Ali <48380998+aliseyalvi@users.noreply.github.com> Date: Fri, 29 Sep 2023 18:39:20 +0500 Subject: [PATCH 023/111] added post description field in post options modal --- src/config/locales/en-US.json | 3 +- .../editor/children/postDescription.tsx | 34 +++++++++++++++++++ .../editor/children/postOptionsModal.tsx | 6 ++++ src/screens/editor/children/styles.ts | 9 +++++ 4 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/screens/editor/children/postDescription.tsx diff --git a/src/config/locales/en-US.json b/src/config/locales/en-US.json index caca4e858..a27de564f 100644 --- a/src/config/locales/en-US.json +++ b/src/config/locales/en-US.json @@ -530,7 +530,8 @@ "invalid_url_error":"Please insert valid url", "plain":"Plain", "video":"Video", - "image":"Image" + "image":"Image", + "short_desc": "Short description" }, "snippets":{ "label_no_snippets":"No Snippets Found", diff --git a/src/screens/editor/children/postDescription.tsx b/src/screens/editor/children/postDescription.tsx new file mode 100644 index 000000000..a2e660d1a --- /dev/null +++ b/src/screens/editor/children/postDescription.tsx @@ -0,0 +1,34 @@ +import React from 'react'; +import { useIntl } from 'react-intl'; +import { Text, View } from 'react-native'; +import { TextInput } from '../../../components'; + +import styles from './styles'; + +interface PostDescriptionProps { + postDescription: string; + handlePostDescriptionChange: (value: string) => void; +} + +const PostDescription = ({ + postDescription, + handlePostDescriptionChange, +}: PostDescriptionProps) => { + const intl = useIntl(); + + return ( + + {intl.formatMessage({ id: 'editor.short_desc' })} + + + ); +}; + +export default PostDescription; diff --git a/src/screens/editor/children/postOptionsModal.tsx b/src/screens/editor/children/postOptionsModal.tsx index e7a97c872..0ed782f6e 100644 --- a/src/screens/editor/children/postOptionsModal.tsx +++ b/src/screens/editor/children/postOptionsModal.tsx @@ -12,6 +12,7 @@ import { } from '../../../components'; import styles from './postOptionsModalStyles'; import ThumbSelectionContent from './thumbSelectionContent'; +import PostDescription from './postDescription'; const REWARD_TYPES = [ { @@ -73,6 +74,7 @@ const PostOptionsModal = forwardRef( const [shouldReblog, setShouldReblog] = useState(false); const [scheduledFor, setScheduledFor] = useState(''); const [disableDone, setDisableDone] = useState(false); + const [postDescription, setPostDescription] = useState(''); // removed the useeffect causing index reset bug @@ -194,6 +196,10 @@ const PostOptionsModal = forwardRef( isUploading={isUploading} onThumbSelection={_handleThumbIndexSelection} /> + {!isEdit && ( diff --git a/src/screens/editor/children/styles.ts b/src/screens/editor/children/styles.ts index ad7a2620c..5e298e20b 100644 --- a/src/screens/editor/children/styles.ts +++ b/src/screens/editor/children/styles.ts @@ -57,4 +57,13 @@ export default EStyleSheet.create({ thumbSelectContainer: { marginTop: 12, }, + input: { + borderWidth: 1, + borderColor: '$borderColor', + borderRadius: 8, + paddingHorizontal: 10, + color: '$primaryBlack', + marginVertical: 8, + height: 60, + }, }); From d9abcac9df3d5e81a22526718987a29394b7cf37 Mon Sep 17 00:00:00 2001 From: Sadaqat Ali <48380998+aliseyalvi@users.noreply.github.com> Date: Sun, 1 Oct 2023 12:41:40 +0500 Subject: [PATCH 024/111] * added description field in meta * load description from meta into post description field * save post description to meta from post description field in post options modal --- .../editor/children/postDescription.tsx | 1 + .../editor/children/postOptionsModal.tsx | 7 +++++-- .../editor/container/editorContainer.tsx | 20 +++++++++++++++++-- src/screens/editor/screen/editorScreen.tsx | 12 ++++++++++- 4 files changed, 35 insertions(+), 5 deletions(-) diff --git a/src/screens/editor/children/postDescription.tsx b/src/screens/editor/children/postDescription.tsx index a2e660d1a..dad64aa00 100644 --- a/src/screens/editor/children/postDescription.tsx +++ b/src/screens/editor/children/postDescription.tsx @@ -24,6 +24,7 @@ const PostDescription = ({ value={postDescription} onChangeText={handlePostDescriptionChange} autoCapitalize="none" + maxLength={255} editable multiline /> diff --git a/src/screens/editor/children/postOptionsModal.tsx b/src/screens/editor/children/postOptionsModal.tsx index 0ed782f6e..cbf58aac6 100644 --- a/src/screens/editor/children/postOptionsModal.tsx +++ b/src/screens/editor/children/postOptionsModal.tsx @@ -40,8 +40,10 @@ interface PostOptionsModalProps { isEdit: boolean; isCommunityPost: boolean; rewardType: string; + postDescription: string; isUploading: boolean; handleRewardChange: (rewardType: string) => void; + handlePostDescriptionChange: (value: string) => void; handleThumbSelection: (url: string) => void; handleScheduleChange: (datetime: string | null) => void; handleShouldReblogChange: (shouldReblog: boolean) => void; @@ -57,12 +59,14 @@ const PostOptionsModal = forwardRef( isEdit, isCommunityPost, rewardType, + postDescription, isUploading, handleRewardChange, handleThumbSelection, handleScheduleChange, handleShouldReblogChange, handleFormUpdate, + handlePostDescriptionChange, }: PostOptionsModalProps, ref, ) => { @@ -74,7 +78,6 @@ const PostOptionsModal = forwardRef( const [shouldReblog, setShouldReblog] = useState(false); const [scheduledFor, setScheduledFor] = useState(''); const [disableDone, setDisableDone] = useState(false); - const [postDescription, setPostDescription] = useState(''); // removed the useeffect causing index reset bug @@ -198,7 +201,7 @@ const PostOptionsModal = forwardRef( /> {!isEdit && ( diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 8a95f63dd..f8d5b228c 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -88,6 +88,7 @@ class EditorContainer extends Component { onLoadDraftPress: false, thumbUrl: '', shouldReblog: false, + postDescription: '', }; } @@ -194,7 +195,8 @@ class EditorContainer extends Component { componentDidUpdate(prevProps: Readonly, prevState: Readonly): void { if ( prevState.rewardType !== this.state.rewardType || - prevProps.beneficiariesMap !== this.props.beneficiariesMap + prevProps.beneficiariesMap !== this.props.beneficiariesMap || + prevState.postDescription !== this.state.postDescription ) { // update isDraftSaved when reward type or beneficiaries are changed in post options this._handleFormChanged(); @@ -290,6 +292,12 @@ class EditorContainer extends Component { }); } + if (draft.meta && draft.meta.description) { + this.setState({ + postDescription: draft.meta.description, + }); + } + if (draft._id && draft.meta && draft.meta.beneficiaries) { if (isArray(draft.meta.beneficiaries)) { const filteredBeneficiaries = draft.meta.beneficiaries.filter( @@ -398,7 +406,7 @@ class EditorContainer extends Component { }; _saveDraftToDB = async (fields, saveAsNew = false) => { - const { isDraftSaved, draftId, thumbUrl, isReply, rewardType } = this.state; + const { isDraftSaved, draftId, thumbUrl, isReply, rewardType, postDescription } = this.state; const { currentAccount, dispatch, intl, queryClient } = this.props; try { @@ -441,6 +449,7 @@ class EditorContainer extends Component { tags: draftField.tags, beneficiaries, rewardType, + description: postDescription, }); const jsonMeta = makeJsonMetadata(meta, draftField.tags); @@ -1090,6 +1099,10 @@ class EditorContainer extends Component { this.setState({ rewardType: value }); }; + _handlePostDescriptionChange = (value: string) => { + this.setState({ postDescription: value }); + }; + _handleShouldReblogChange = (value: boolean) => { this.setState({ shouldReblog: value, @@ -1130,6 +1143,7 @@ class EditorContainer extends Component { thumbUrl, uploadProgress, rewardType, + postDescription, } = this.state; const tags = route.params?.tags; @@ -1171,6 +1185,8 @@ class EditorContainer extends Component { setThumbUrl={this._handleSetThumbUrl} uploadProgress={uploadProgress} rewardType={rewardType} + postDescription={postDescription} + handlePostDescriptionChange={this._handlePostDescriptionChange} getBeneficiaries={this._extractBeneficiaries} setIsUploading={this._setIsUploading} /> diff --git a/src/screens/editor/screen/editorScreen.tsx b/src/screens/editor/screen/editorScreen.tsx index 682afabff..2dececc5e 100644 --- a/src/screens/editor/screen/editorScreen.tsx +++ b/src/screens/editor/screen/editorScreen.tsx @@ -235,6 +235,11 @@ class EditorScreen extends Component { handleRewardChange(value); }; + _handlePostDescriptionChange = (value: string) => { + const { handlePostDescriptionChange } = this.props as any; + handlePostDescriptionChange(value); + }; + _handleSettingsPress = () => { if (this.postOptionsModalRef) { this.postOptionsModalRef.show(); @@ -261,7 +266,8 @@ class EditorScreen extends Component { }; _handleFormUpdate = async (componentID, content) => { - const { handleFormChanged, thumbUrl, rewardType, getBeneficiaries } = this.props; + const { handleFormChanged, thumbUrl, rewardType, getBeneficiaries, postDescription } = + this.props; const { fields: _fields } = this.state; const fields = { ..._fields }; @@ -283,6 +289,7 @@ class EditorScreen extends Component { tags: fields.tags, beneficiaries: getBeneficiaries(), rewardType, + description: postDescription, }); const jsonMeta = makeJsonMetadata(meta, fields.tags); fields.meta = jsonMeta; @@ -415,6 +422,7 @@ class EditorScreen extends Component { thumbUrl, uploadProgress, rewardType, + postDescription, setIsUploading, } = this.props; @@ -527,6 +535,8 @@ class EditorScreen extends Component { isEdit={isEdit} isCommunityPost={selectedCommunity !== null} rewardType={rewardType} + postDescription={postDescription} + handlePostDescriptionChange={this._handlePostDescriptionChange} isUploading={isUploading} handleThumbSelection={this._handleOnThumbSelection} handleRewardChange={this._handleRewardChange} From 46f2c11ce109440091194e91e67572b313198f53 Mon Sep 17 00:00:00 2001 From: Sadaqat Ali <48380998+aliseyalvi@users.noreply.github.com> Date: Sat, 28 Oct 2023 13:42:18 +0500 Subject: [PATCH 025/111] added placeholder for short description input --- src/config/locales/en-US.json | 3 ++- src/screens/editor/children/postDescription.tsx | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/config/locales/en-US.json b/src/config/locales/en-US.json index a27de564f..f99f422c5 100644 --- a/src/config/locales/en-US.json +++ b/src/config/locales/en-US.json @@ -531,7 +531,8 @@ "plain":"Plain", "video":"Video", "image":"Image", - "short_desc": "Short description" + "short_desc": "Short description", + "short_desc_placeholder": "Brief summary of content" }, "snippets":{ "label_no_snippets":"No Snippets Found", diff --git a/src/screens/editor/children/postDescription.tsx b/src/screens/editor/children/postDescription.tsx index dad64aa00..70ad2219e 100644 --- a/src/screens/editor/children/postDescription.tsx +++ b/src/screens/editor/children/postDescription.tsx @@ -25,6 +25,7 @@ const PostDescription = ({ onChangeText={handlePostDescriptionChange} autoCapitalize="none" maxLength={255} + placeholder={intl.formatMessage({ id: 'editor.short_desc_placeholder' })} editable multiline /> From a98ee636c132f3854dc9ecc046fdb6c6d016922f Mon Sep 17 00:00:00 2001 From: Sadaqat Ali <48380998+aliseyalvi@users.noreply.github.com> Date: Sat, 28 Oct 2023 13:47:14 +0500 Subject: [PATCH 026/111] removed extra space from thumbnails list bottom --- src/screens/editor/children/styles.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/screens/editor/children/styles.ts b/src/screens/editor/children/styles.ts index 5e298e20b..6b97e36ff 100644 --- a/src/screens/editor/children/styles.ts +++ b/src/screens/editor/children/styles.ts @@ -33,7 +33,7 @@ export default EStyleSheet.create({ textAlign: 'left', }, listContainer: { - paddingBottom: getBottomSpace() + 16, + paddingBottom: 12, }, container: { paddingVertical: 16, From c82c2e1620cac2d6ce80997c56eb5a2f5a722b48 Mon Sep 17 00:00:00 2001 From: Sadaqat Ali <48380998+aliseyalvi@users.noreply.github.com> Date: Sat, 28 Oct 2023 18:09:07 +0500 Subject: [PATCH 027/111] get description from postBodySummary if description is not present --- .../editor/container/editorContainer.tsx | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index f8d5b228c..7476c1a81 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -1,7 +1,7 @@ import React, { Component } from 'react'; import { connect } from 'react-redux'; import { injectIntl } from 'react-intl'; -import { Alert, AppState, AppStateStatus, NativeEventSubscription } from 'react-native'; +import { Alert, AppState, AppStateStatus, NativeEventSubscription, Platform } from 'react-native'; import get from 'lodash/get'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { isArray } from 'lodash'; @@ -50,6 +50,7 @@ import { useUserActivityMutation } from '../../../providers/queries/pointQueries import { PointActivityIds } from '../../../providers/ecency/ecency.types'; import { usePostsCachePrimer } from '../../../providers/queries/postQueries/postQueries'; import { PostTypes } from '../../../constants/postTypes'; +import { postBodySummary } from '@ecency/render-helper'; /* * Props Name Description Value @@ -449,7 +450,9 @@ class EditorContainer extends Component { tags: draftField.tags, beneficiaries, rewardType, - description: postDescription, + description: postDescription + ? postDescription + : postBodySummary(get(draftField, 'body', ''), 200, Platform.OS as any), }); const jsonMeta = makeJsonMetadata(meta, draftField.tags); @@ -729,9 +732,9 @@ class EditorContainer extends Component { const meta = await extractMetadata({ body: fields.body, fetchRatios: true, - postType: PostTypes.COMMENT - }) - const jsonMetadata = makeJsonMetadata(meta, parentTags || ['ecency']) + postType: PostTypes.COMMENT, + }); + const jsonMetadata = makeJsonMetadata(meta, parentTags || ['ecency']); await postComment( currentAccount, @@ -740,7 +743,7 @@ class EditorContainer extends Component { parentPermlink, permlink, fields.body, - jsonMetadata + jsonMetadata, ) .then((response) => { // record user activity for points @@ -1148,6 +1151,8 @@ class EditorContainer extends Component { const tags = route.params?.tags; const paramFiles = route.params?.files; + console.log('post : ', post); + return ( { handleShouldReblogChange={this._handleShouldReblogChange} handleSchedulePress={this._handleSchedulePress} handleFormChanged={this._handleFormChanged} - handleOnBackPress={() => { }} + handleOnBackPress={() => {}} handleOnSubmit={this._handleSubmit} initialEditor={this._initialEditor} isDarkTheme={isDarkTheme} From d21c7ce595e8ba423391fddaf1b9fea5aec8f5d2 Mon Sep 17 00:00:00 2001 From: Sadaqat Ali <48380998+aliseyalvi@users.noreply.github.com> Date: Sat, 28 Oct 2023 18:22:20 +0500 Subject: [PATCH 028/111] set post body description on saving draft --- src/screens/editor/container/editorContainer.tsx | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 7476c1a81..6c444815b 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -423,7 +423,12 @@ class EditorContainer extends Component { } const beneficiaries = this._extractBeneficiaries(); - + const postBodySummaryContent = postBodySummary( + get(fields, 'body', ''), + 200, + Platform.OS as any, + ); + this._handlePostDescriptionChange(postBodySummaryContent); try { if (!isDraftSaved) { let draftField; @@ -450,10 +455,9 @@ class EditorContainer extends Component { tags: draftField.tags, beneficiaries, rewardType, - description: postDescription - ? postDescription - : postBodySummary(get(draftField, 'body', ''), 200, Platform.OS as any), + description: postDescription ? postDescription : postBodySummaryContent, }); + const jsonMeta = makeJsonMetadata(meta, draftField.tags); // update draft is draftId is present From 7cacc4bc9767ec2d410683f5f9a091ec45720f5c Mon Sep 17 00:00:00 2001 From: Sadaqat Ali <48380998+aliseyalvi@users.noreply.github.com> Date: Sat, 28 Oct 2023 18:25:27 +0500 Subject: [PATCH 029/111] removed console log --- src/screens/editor/container/editorContainer.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 6c444815b..a9d21235e 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -1155,7 +1155,6 @@ class EditorContainer extends Component { const tags = route.params?.tags; const paramFiles = route.params?.files; - console.log('post : ', post); return ( Date: Thu, 2 Nov 2023 12:07:08 +0500 Subject: [PATCH 030/111] lint rules update --- .eslintrc.json | 49 ++++++++++++++++++++++++++++++++++++++---------- ios/Podfile.lock | 2 +- package.json | 4 ++-- 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index fb854bebe..4e756bd32 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,8 +1,9 @@ { - "parser": "babel-eslint", + "parser": "@typescript-eslint/parser", "extends": [ "airbnb", "prettier", + "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended", "plugin:eslint-comments/recommended", "eslint:recommended", @@ -28,19 +29,44 @@ "jest", "eslint-comments" ], + "parserOptions": { + "ecmaFeatures": { + "jsx": true + } + }, + "settings": { + ":react-native/style-sheet-object-names": ["EStyleSheet"] + }, "rules": { "react/jsx-filename-extension": [ 2, { - "extensions": [".js", ".jsx", ".ts", ".tsx"] + "extensions": [ + ".js", + ".jsx", + ".ts", + ".tsx" + ] } ], - "max-len": ["warn", 100], - "react/forbid-prop-types": [0], + "max-len": [ + "warn", + 100 + ], + "react/forbid-prop-types": [ + 0 + ], "no-underscore-dangle": 0, - "react/require-default-props": [0], - "global-require": [0], - "func-names": ["error", "as-needed"], + "react/require-default-props": [ + 0 + ], + "global-require": [ + 0 + ], + "func-names": [ + "error", + "as-needed" + ], "linebreak-style": 0, "no-use-before-define": "off", "import/prefer-default-export": "off", @@ -51,7 +77,10 @@ "import/no-cycle": "off", "react-hooks/rules-of-hooks": "warn", "react-hooks/exhaustive-deps": "off", - "react/destructuring-assignment": [1, "always"], + "react/destructuring-assignment": [ + 1, + "always" + ], "import/no-extraneous-dependencies": [ "error", { @@ -68,6 +97,6 @@ "ts": "never", "tsx": "never" } - ] + ] } -} +} \ No newline at end of file diff --git a/ios/Podfile.lock b/ios/Podfile.lock index d079d3c6d..5eb2d968e 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -1118,4 +1118,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 6b212d63236c21489948e9b73b59fcff2feeeb08 -COCOAPODS: 1.13.0 +COCOAPODS: 1.11.3 diff --git a/package.json b/package.json index 89ee87fff..d3f5d1824 100644 --- a/package.json +++ b/package.json @@ -16,8 +16,8 @@ "ios": "react-native run-ios", "releasenotes": "./release-notes.sh > release-notes.txt; node -e 'console.log(JSON.stringify(require(\"fs\").readFileSync(\"release-notes.txt\", \"utf8\")));' > release-notes.json", "test": "node node_modules/jest/bin/jest.js --watch", - "lint": "eslint src/", - "lint:fix": "eslint src/ --fix", + "lint": "eslint src/ --ext .js,.jsx,.ts,.tsx", + "lint:fix": "eslint src/ --fix --ext .js,.jsx,.ts,.tsx", "format": "prettier --write 'src/**/*.{js,jsx,ts,tsx}' && yarn lint:fix --fix", "lint-staged": "lint-staged", "clear": "watchman watch-del-all && rm -rf $TMPDIR/react-native-packager-cache-* && rm -rf $TMPDIR/metro-bundler-cache-* && rm -rf node_modules/ && yarn && yarn start -- --reset-cache", From c4fca1e793f0fa374d43d0b61f826f0a66536bba Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 12:07:22 +0500 Subject: [PATCH 031/111] 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`; From df1d6cb2bcb2e4def427ce34715c01396f9cb10a Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 13:54:22 +0500 Subject: [PATCH 032/111] using Number.isNan --- src/components/autoHeightImage/autoHeightImage.tsx | 2 +- src/utils/vote.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/components/autoHeightImage/autoHeightImage.tsx b/src/components/autoHeightImage/autoHeightImage.tsx index ec343317b..34104fde9 100644 --- a/src/components/autoHeightImage/autoHeightImage.tsx +++ b/src/components/autoHeightImage/autoHeightImage.tsx @@ -28,7 +28,7 @@ export const AutoHeightImage = ({ metadata.image_ratios.forEach((_ratio, index) => { const url = metadata.image[index]; - if (url && !isNaN(_ratio)) { + if (url && !Number.isNaN(_ratio)) { const poxifiedUrl = proxifyImageSrc( url, undefined, diff --git a/src/utils/vote.ts b/src/utils/vote.ts index 63d594fdf..d36b9ce53 100644 --- a/src/utils/vote.ts +++ b/src/utils/vote.ts @@ -12,7 +12,7 @@ export const getEstimatedAmount = (account, globalProps: GlobalProps, sliderValu const voteValue = (voteEffectiveShares / fundRecentClaims) * fundRewardBalance * hbdMedian; const estimatedAmount = weight < 0 ? Math.min(voteValue * -1, 0) : Math.max(voteValue, 0); - if (isNaN(estimatedAmount)) { + if (Number.isNaN(estimatedAmount)) { return '0.00'; } else if (estimatedAmount >= 1) { return estimatedAmount.toFixed(2); From 3b57e8ad7dc96a9164073c96128b9c88afcdda49 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 13:56:04 +0500 Subject: [PATCH 033/111] using ** operation instead of math.pow --- src/providers/hive-engine/converters.ts | 2 +- src/utils/number.ts | 2 +- src/utils/postParser.tsx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/providers/hive-engine/converters.ts b/src/providers/hive-engine/converters.ts index f043f583f..8eb9e36d1 100644 --- a/src/providers/hive-engine/converters.ts +++ b/src/providers/hive-engine/converters.ts @@ -55,7 +55,7 @@ export const convertRewardsStatus = (rawData: any) => { symbol: rawData.symbol, pendingToken: rawData.pending_token, precision: rawData.precision, - pendingRewards: rawData.pending_token / Math.pow(10, rawData.precision), + pendingRewards: rawData.pending_token / (10 ** rawData.precision), } as TokenStatus; }; diff --git a/src/utils/number.ts b/src/utils/number.ts index 97c3a9f36..d85822b1e 100644 --- a/src/utils/number.ts +++ b/src/utils/number.ts @@ -15,7 +15,7 @@ export const stripDecimalPlaces = (value: number, precision = 3) => { return 0; } - const power = Math.pow(10, precision); + const power = 10 ** precision; return Math.floor(value * power) / power; }; diff --git a/src/utils/postParser.tsx b/src/utils/postParser.tsx index d8b106c69..6b45cdc70 100644 --- a/src/utils/postParser.tsx +++ b/src/utils/postParser.tsx @@ -56,7 +56,7 @@ export const parsePost = ( // find and inject thumbnail ratio if (post.json_metadata.image_ratios) { - if (!isNaN(post.json_metadata.image_ratios[0])) { + if (!Number.isNaN(post.json_metadata.image_ratios[0])) { post.thumbRatio = post.json_metadata.image_ratios[0]; } } From ffdb1ccbaf9168d586dd192c90341b1980b87feb Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 14:01:30 +0500 Subject: [PATCH 034/111] using ** --- src/providers/hive-engine/converters.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/providers/hive-engine/converters.ts b/src/providers/hive-engine/converters.ts index 8eb9e36d1..42cdebd02 100644 --- a/src/providers/hive-engine/converters.ts +++ b/src/providers/hive-engine/converters.ts @@ -55,7 +55,7 @@ export const convertRewardsStatus = (rawData: any) => { symbol: rawData.symbol, pendingToken: rawData.pending_token, precision: rawData.precision, - pendingRewards: rawData.pending_token / (10 ** rawData.precision), + pendingRewards: rawData.pending_token / 10 ** rawData.precision, } as TokenStatus; }; From 229780e561fa2ff6802eef9ccbe891a6202e7ab8 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 14:11:57 +0500 Subject: [PATCH 035/111] post parser lint error fixes --- src/utils/postParser.tsx | 74 +++++++++++++++++++--------------------- 1 file changed, 36 insertions(+), 38 deletions(-) diff --git a/src/utils/postParser.tsx b/src/utils/postParser.tsx index 6b45cdc70..4cdeb391d 100644 --- a/src/utils/postParser.tsx +++ b/src/utils/postParser.tsx @@ -1,5 +1,4 @@ -import isEmpty from 'lodash/isEmpty'; -import forEach from 'lodash/forEach'; + import { get, isArray } from 'lodash'; import { Platform } from 'react-native'; import { postBodySummary, renderPostBody, catchPostImage } from '@ecency/render-helper'; @@ -10,7 +9,7 @@ import parseAsset from './parseAsset'; import { getResizedAvatar } from './image'; import { parseReputation } from './user'; import { CacheStatus } from '../redux/reducers/cacheReducer'; -import { calculateVoteReward, getEstimatedAmount } from './vote'; +import { calculateVoteReward } from './vote'; const webp = Platform.OS !== 'ios'; @@ -57,7 +56,7 @@ export const parsePost = ( // find and inject thumbnail ratio if (post.json_metadata.image_ratios) { if (!Number.isNaN(post.json_metadata.image_ratios[0])) { - post.thumbRatio = post.json_metadata.image_ratios[0]; + [post.thumbRatio] = post.json_metadata.image_ratios; } } @@ -94,18 +93,18 @@ export const parsePost = ( }; export const parseDiscussionCollection = async (commentsMap: { [key: string]: any }) => { - for (const key in commentsMap) { - if (commentsMap.hasOwnProperty(key)) { - const comment = commentsMap[key]; + Object.keys(commentsMap).forEach((key) => { - // prcoess first level comment - if (comment) { - commentsMap[key] = parseComment(comment); - } else { - delete commentsMap[key]; - } + const comment = commentsMap[key]; + + // prcoess first level comment + if (comment) { + commentsMap[key] = parseComment(comment); + } else { + delete commentsMap[key]; } - } + + }) console.log('parsed discussion collection', commentsMap); return commentsMap; @@ -137,18 +136,18 @@ export const parseCommentThreads = async (commentsMap: any, author: string, perm return []; }; - for (const key in commentsMap) { - if (commentsMap.hasOwnProperty(key)) { - const comment = commentsMap[key]; + Object.keys(commentsMap).forEach((key) => { - // prcoess first level comment - if (comment && comment.parent_author === author && comment.parent_permlink === permlink) { - const _parsedComment = parseComment(comment); - _parsedComment.replies = parseReplies(commentsMap, _parsedComment.replies, 1); - comments.push(_parsedComment); - } + const comment = commentsMap[key]; + + // prcoess first level comment + if (comment && comment.parent_author === author && comment.parent_permlink === permlink) { + const _parsedComment = parseComment(comment); + _parsedComment.replies = parseReplies(commentsMap, _parsedComment.replies, 1); + comments.push(_parsedComment); } - } + + }) return comments; }; @@ -181,17 +180,15 @@ export const mapDiscussionToThreads = async ( return []; }; - for (const key in commentsMap) { - if (commentsMap.hasOwnProperty(key)) { - const comment = commentsMap[key]; + Object.keys(commentsMap).forEach((key) => { + const comment = commentsMap[key]; - // prcoess first level comment - if (comment && comment.parent_author === author && comment.parent_permlink === permlink) { - comment.replies = parseReplies(commentsMap, comment.replies, 1); - comments.push(comment); - } + // prcoess first level comment + if (comment && comment.parent_author === author && comment.parent_permlink === permlink) { + comment.replies = parseReplies(commentsMap, comment.replies, 1); + comments.push(comment); } - } + }) return comments; }; @@ -257,16 +254,17 @@ export const injectPostCache = (commentsMap, cachedComments, cachedVotes, lastCa } // process votes cache - for (const path in cachedVotes) { + Object.keys(cachedVotes).forEach((path) => { const cachedVote = cachedVotes[path]; if (_comments[path]) { console.log('injection vote cache'); _comments[path] = injectVoteCache(_comments[path], cachedVote); } - } + }) // process comments cache - for (const path in cachedComments) { + + Object.keys(cachedComments).forEach((path) => { const currentTime = new Date().getTime(); const cachedComment = cachedComments[path]; const _parentPath = `${cachedComment.parent_author}/${cachedComment.parent_permlink}`; @@ -298,7 +296,7 @@ export const injectPostCache = (commentsMap, cachedComments, cachedVotes, lastCa // in this case add comment key in childern and inject cachedComment in commentsMap _comments[path] = cachedComment; _comments[_parentPath].replies.push(path); - _comments[_parentPath].children = _comments[_parentPath].children + 1; + _comments[_parentPath].children += 1; // if comment was created very recently enable auto reveal if (lastCacheUpdate.postPath === path && currentTime - lastCacheUpdate.updatedAt < 5000) { @@ -309,7 +307,7 @@ export const injectPostCache = (commentsMap, cachedComments, cachedVotes, lastCa } break; } - } + }) return shouldClone ? { ..._comments } : _comments; }; From 066504ebd6a11abb34a31fa7c48b4da31a3ada3a Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 14:15:51 +0500 Subject: [PATCH 036/111] hive uri, wallet, migration error fixes --- src/utils/hive-uri.ts | 26 +++++++++++++------------- src/utils/migrationHelpers.ts | 5 ++--- src/utils/wallet.ts | 1 - 3 files changed, 15 insertions(+), 17 deletions(-) diff --git a/src/utils/hive-uri.ts b/src/utils/hive-uri.ts index 74c812ec5..0ba36664b 100644 --- a/src/utils/hive-uri.ts +++ b/src/utils/hive-uri.ts @@ -1,6 +1,6 @@ import { get, isArray } from 'lodash'; -const operationsData = require('./operations.json'); +import * as operationsData from './operations.json'; /** * checks if uri entered is valid hive uri @@ -19,16 +19,17 @@ const _checkOpsArray = (ops: any) => { }; const findParentKey = (obj, value, parentKey = null) => { - for (const key in obj) { - if (obj[key] === value) { - return parentKey; - } else if (typeof obj[key] === 'object') { - const foundKey = findParentKey(obj[key], value, key); - if (foundKey) { - return foundKey; + + Object.keys(obj).forEach((key) => { + if (obj[key] === value) { + return parentKey; + } else if (typeof obj[key] === 'object') { + const foundKey = findParentKey(obj[key], value, key); + if (foundKey) { + return foundKey; + } } - } - } + }) return null; }; @@ -68,7 +69,6 @@ const _formatAmount = (amount: string) => { * * */ export const getFormattedTx = (tx: any, authoritiesMap: Map) => { - let opName; const errorObj = { errorKey1: '', errorKey2: '', @@ -105,7 +105,7 @@ export const getFormattedTx = (tx: any, authoritiesMap: Map) => return Promise.reject(errorObj); } // if amount field present in operation, validate and check for proper formatting and format to 3 decimal places - if (operationObj.hasOwnProperty('amount')) { + if (!!operationObj?.amount) { const amount = _formatAmount(operationObj.amount); operationObj.amount = amount; if (!amount) { @@ -120,7 +120,7 @@ export const getFormattedTx = (tx: any, authoritiesMap: Map) => operationObj[opProps.signerField] = '__signer'; } - opName = opProps.opName; + const { opName } = opProps; tx = { ...tx, operations: [[operationName, operationObj]], diff --git a/src/utils/migrationHelpers.ts b/src/utils/migrationHelpers.ts index 4264b34ef..7e8ce712b 100644 --- a/src/utils/migrationHelpers.ts +++ b/src/utils/migrationHelpers.ts @@ -45,7 +45,6 @@ import { toastNotification, } from '../redux/actions/uiAction'; import { decryptKey, encryptKey } from './crypto'; -import { Draft } from '../redux/reducers/cacheReducer'; import { delay } from './editor'; import RootNavigation from '../navigation/rootNavigation'; import ROUTES from '../constants/routeNames'; @@ -135,7 +134,7 @@ export const migrateUserEncryption = async (dispatch, currentAccount, encUserPin let _currentAccount = currentAccount; _currentAccount.username = _currentAccount.name; - _currentAccount.local = realmData[0]; + [_currentAccount.local] = realmData; try { const pinHash = encryptKey(Config.DEFAULT_PIN, Config.PIN_KEY); @@ -213,7 +212,7 @@ export const repairUserAccountData = async (username, dispatch, intl, accounts, { text: intl.formatMessage({ id: 'alert.cancel' }), style: 'destructive', - onPress: () => {}, + onPress: () => {console.log("cancel pressed")}, }, { text: intl.formatMessage({ id: 'alert.verify' }), diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 0470287d3..73e5390e6 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -668,7 +668,6 @@ const _fetchSpkWalletData = async ( username: string, hivePrice: number, vsCurrency: string, - claimsCache: ClaimsCollection, ) => { const spkWalletData: { [key: string]: CoinData } = {}; From dcf4b52b96435d20dc2c506032c075712b1de51f Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 15:44:05 +0500 Subject: [PATCH 037/111] no empty function --- src/components/basicHeader/view/basicHeaderView.tsx | 2 +- src/components/beneficiaryModal/beneficiaryModal.tsx | 2 +- src/components/comments/container/commentsContainer.tsx | 2 +- .../postOptionsModal/container/postOptionsModal.tsx | 2 +- src/components/qrModal/qrModalView.tsx | 2 +- src/components/sideMenu/view/sideMenuView.js | 2 +- .../uploadsGalleryModal/container/uploadsGalleryModal.tsx | 2 +- src/containers/profileContainer.js | 2 +- src/screens/editor/container/editorContainer.tsx | 2 +- src/screens/editor/screen/editorScreen.tsx | 2 +- src/screens/settings/container/settingsContainer.tsx | 4 ++-- src/screens/trade/children/swapTokenContent.tsx | 2 +- src/screens/transfer/screen/transferScreen.js | 2 +- src/screens/voters/screen/votersScreen.js | 2 +- 14 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/components/basicHeader/view/basicHeaderView.tsx b/src/components/basicHeader/view/basicHeaderView.tsx index a73620f2a..46f0ae7a7 100644 --- a/src/components/basicHeader/view/basicHeaderView.tsx +++ b/src/components/basicHeader/view/basicHeaderView.tsx @@ -66,7 +66,7 @@ const BasicHeaderView = ({ } }; - const _handleOnDropdownSelect = () => {}; + const _handleOnDropdownSelect = () => {console.log("pressed")}; const _handleSearchButtonPress = () => { setIsInputVisible(!isInputVisible); diff --git a/src/components/beneficiaryModal/beneficiaryModal.tsx b/src/components/beneficiaryModal/beneficiaryModal.tsx index 0efe6945d..1c77f9cb0 100644 --- a/src/components/beneficiaryModal/beneficiaryModal.tsx +++ b/src/components/beneficiaryModal/beneficiaryModal.tsx @@ -147,7 +147,7 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { inputStyle={styles.weightFormInput} wrapperStyle={styles.weightFormInputWrapper} onChange={(value) => _onWeightInputChange(value)} - onBlur={() => {}} // _onBlur(item)} + onBlur={() => {console.log("pressed")}} // _onBlur(item)} keyboardType="numeric" /> diff --git a/src/components/comments/container/commentsContainer.tsx b/src/components/comments/container/commentsContainer.tsx index 1471eb9b2..9c4a3ad56 100644 --- a/src/components/comments/container/commentsContainer.tsx +++ b/src/components/comments/container/commentsContainer.tsx @@ -172,7 +172,7 @@ const CommentsContainer = ({ handleOnCommentsLoaded(); } }) - .catch(() => {}); + .catch(() => {console.log("cancel pressed")}); } }; diff --git a/src/components/postOptionsModal/container/postOptionsModal.tsx b/src/components/postOptionsModal/container/postOptionsModal.tsx index c9bc00be5..be39ae8c3 100644 --- a/src/components/postOptionsModal/container/postOptionsModal.tsx +++ b/src/components/postOptionsModal/container/postOptionsModal.tsx @@ -228,7 +228,7 @@ const PostOptionsModal = ({ pageType }: Props, ref) => { buttons: [ { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {}, + onPress: () => {console.log("cancel pressed")}, }, { text: intl.formatMessage({ id: 'alert.confirm' }), diff --git a/src/components/qrModal/qrModalView.tsx b/src/components/qrModal/qrModalView.tsx index adabb7912..cf6a30f7d 100644 --- a/src/components/qrModal/qrModalView.tsx +++ b/src/components/qrModal/qrModalView.tsx @@ -181,7 +181,7 @@ export const QRModal = ({}: QRModalProps) => { text: intl.formatMessage({ id: 'qr.cancel', }), - onPress: () => {}, + onPress: () => {console.log("cancel pressed")}, style: 'cancel', }, { diff --git a/src/components/sideMenu/view/sideMenuView.js b/src/components/sideMenu/view/sideMenuView.js index 88d0234be..d2393cd08 100644 --- a/src/components/sideMenu/view/sideMenuView.js +++ b/src/components/sideMenu/view/sideMenuView.js @@ -78,7 +78,7 @@ const SideMenuView = ({ buttons: [ { text: intl.formatMessage({ id: 'side_menu.cancel' }), - onPress: () => {}, + onPress: () => {console.log("cancel pressed")}, }, { text: intl.formatMessage({ id: 'side_menu.logout' }), diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 861d368e6..225136453 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -332,7 +332,7 @@ export const UploadsGalleryModal = forwardRef( let body = error.message || JSON.stringify(error); let action: AlertButton = { text: intl.formatMessage({ id: 'alert.okay' }), - onPress: () => { }, + onPress: () => {console.log("cancel pressed")}, }; switch (error.code) { diff --git a/src/containers/profileContainer.js b/src/containers/profileContainer.js index 4589cd54f..7a3b19f94 100644 --- a/src/containers/profileContainer.js +++ b/src/containers/profileContainer.js @@ -428,7 +428,7 @@ class ProfileContainer extends Component { buttons: [ { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {}, + onPress: () => {console.log("cancel pressed")}, }, { text: intl.formatMessage({ id: 'alert.confirm' }), diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index a9d21235e..af72c0eb8 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -1165,7 +1165,7 @@ class EditorContainer extends Component { handleShouldReblogChange={this._handleShouldReblogChange} handleSchedulePress={this._handleSchedulePress} handleFormChanged={this._handleFormChanged} - handleOnBackPress={() => {}} + handleOnBackPress={() => {console.log("cancel pressed")}} handleOnSubmit={this._handleSubmit} initialEditor={this._initialEditor} isDarkTheme={isDarkTheme} diff --git a/src/screens/editor/screen/editorScreen.tsx b/src/screens/editor/screen/editorScreen.tsx index 2dececc5e..6a4219ebe 100644 --- a/src/screens/editor/screen/editorScreen.tsx +++ b/src/screens/editor/screen/editorScreen.tsx @@ -181,7 +181,7 @@ class EditorScreen extends Component { }, { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {}, + onPress: () => {console.log("cancel pressed")}, style: 'cancel', }, ]); diff --git a/src/screens/settings/container/settingsContainer.tsx b/src/screens/settings/container/settingsContainer.tsx index c514407b4..051e325e0 100644 --- a/src/screens/settings/container/settingsContainer.tsx +++ b/src/screens/settings/container/settingsContainer.tsx @@ -320,7 +320,7 @@ class SettingsContainer extends Component { buttons: [ { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {}, + onPress: () => {console.log("cancel pressed")}, type: 'destructive', }, { @@ -458,7 +458,7 @@ class SettingsContainer extends Component { buttons: [ { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {}, + onPress: () => {console.log("cancel pressed")}, }, { text: intl.formatMessage({ id: 'alert.delete' }), diff --git a/src/screens/trade/children/swapTokenContent.tsx b/src/screens/trade/children/swapTokenContent.tsx index 44ebb6299..cf06e2758 100644 --- a/src/screens/trade/children/swapTokenContent.tsx +++ b/src/screens/trade/children/swapTokenContent.tsx @@ -211,7 +211,7 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }: }, ), buttons: [ - { textId: 'alert.cancel', onPress: () => {} }, + { textId: 'alert.cancel', onPress: () => {console.log("cancel pressed")} }, { textId: 'alert.confirm', onPress: _confirmSwap }, ], }), diff --git a/src/screens/transfer/screen/transferScreen.js b/src/screens/transfer/screen/transferScreen.js index 93d13850d..e95b85c78 100644 --- a/src/screens/transfer/screen/transferScreen.js +++ b/src/screens/transfer/screen/transferScreen.js @@ -247,7 +247,7 @@ const TransferView = ({ buttons: [ { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {}, + onPress: () => {console.log("cancel pressed")}, }, { text: intl.formatMessage({ id: 'alert.confirm' }), diff --git a/src/screens/voters/screen/votersScreen.js b/src/screens/voters/screen/votersScreen.js index 35e06ea4c..c6dc91e49 100644 --- a/src/screens/voters/screen/votersScreen.js +++ b/src/screens/voters/screen/votersScreen.js @@ -33,7 +33,7 @@ const VotersScreen = ({ route }) => { post.active_votes = parseActiveVotes({ ...post, active_votes: result }); setPost({ ...post }); }) - .catch(() => {}); + .catch(() => {console.log("cancel pressed")}); } }, [route.params?.content]); From ee26dbcddbdeb33ab42aaab900056e40c8992b31 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 15:44:31 +0500 Subject: [PATCH 038/111] organise imports --- src/utils/editor.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/utils/editor.ts b/src/utils/editor.ts index 31351b853..43ce859bf 100644 --- a/src/utils/editor.ts +++ b/src/utils/editor.ts @@ -1,8 +1,8 @@ -import getSlug from 'speakingurl'; -import { Image } from 'react-native'; import { diff_match_patch as diffMatchPatch } from 'diff-match-patch'; -import VersionNumber from 'react-native-version-number'; import MimeTypes from 'mime-types'; +import { Image } from 'react-native'; +import VersionNumber from 'react-native-version-number'; +import getSlug from 'speakingurl'; import { PostTypes } from '../constants/postTypes'; import { ThreeSpeakVideo } from '../providers/speak/speak.types'; @@ -36,7 +36,7 @@ export const generatePermlink = (title, random = false) => { if (perm.length > 255) { perm = perm.substring(perm.length - 255, perm.length); } - + // only letters numbers and dashes perm = perm.toLowerCase().replace(/[^a-z0-9-]+/g, ''); From 5d792294dc64ae8e258dac7254325628728482db Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 15:50:32 +0500 Subject: [PATCH 039/111] empty function body fixes --- .../basicHeader/view/basicHeaderView.tsx | 4 +++- .../beneficiaryModal/beneficiaryModal.tsx | 4 +++- .../comments/container/commentsContainer.tsx | 4 +++- .../container/postOptionsModal.tsx | 4 +++- src/components/qrModal/qrModalView.tsx | 4 +++- src/components/sideMenu/view/sideMenuView.js | 4 +++- .../container/uploadsGalleryModal.tsx | 4 +++- src/containers/profileContainer.js | 4 +++- .../editor/container/editorContainer.tsx | 4 +++- src/screens/editor/screen/editorScreen.tsx | 4 +++- .../settings/container/settingsContainer.tsx | 8 +++++-- .../trade/children/swapTokenContent.tsx | 7 ++++++- src/screens/transfer/screen/transferScreen.js | 4 +++- src/screens/voters/screen/votersScreen.js | 4 +++- src/utils/crypto.js | 2 +- src/utils/editor.ts | 2 +- src/utils/hive-uri.ts | 21 +++++++++---------- src/utils/migrationHelpers.ts | 4 +++- src/utils/postParser.tsx | 15 +++++-------- src/utils/wallet.ts | 6 +----- 20 files changed, 69 insertions(+), 44 deletions(-) diff --git a/src/components/basicHeader/view/basicHeaderView.tsx b/src/components/basicHeader/view/basicHeaderView.tsx index 46f0ae7a7..58103a96a 100644 --- a/src/components/basicHeader/view/basicHeaderView.tsx +++ b/src/components/basicHeader/view/basicHeaderView.tsx @@ -66,7 +66,9 @@ const BasicHeaderView = ({ } }; - const _handleOnDropdownSelect = () => {console.log("pressed")}; + const _handleOnDropdownSelect = () => { + console.log('pressed'); + }; const _handleSearchButtonPress = () => { setIsInputVisible(!isInputVisible); diff --git a/src/components/beneficiaryModal/beneficiaryModal.tsx b/src/components/beneficiaryModal/beneficiaryModal.tsx index 1c77f9cb0..09c86da67 100644 --- a/src/components/beneficiaryModal/beneficiaryModal.tsx +++ b/src/components/beneficiaryModal/beneficiaryModal.tsx @@ -147,7 +147,9 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { inputStyle={styles.weightFormInput} wrapperStyle={styles.weightFormInputWrapper} onChange={(value) => _onWeightInputChange(value)} - onBlur={() => {console.log("pressed")}} // _onBlur(item)} + onBlur={() => { + console.log('pressed'); + }} // _onBlur(item)} keyboardType="numeric" /> diff --git a/src/components/comments/container/commentsContainer.tsx b/src/components/comments/container/commentsContainer.tsx index 9c4a3ad56..1aa10eacf 100644 --- a/src/components/comments/container/commentsContainer.tsx +++ b/src/components/comments/container/commentsContainer.tsx @@ -172,7 +172,9 @@ const CommentsContainer = ({ handleOnCommentsLoaded(); } }) - .catch(() => {console.log("cancel pressed")}); + .catch(() => { + console.log('cancel pressed'); + }); } }; diff --git a/src/components/postOptionsModal/container/postOptionsModal.tsx b/src/components/postOptionsModal/container/postOptionsModal.tsx index be39ae8c3..c3052499b 100644 --- a/src/components/postOptionsModal/container/postOptionsModal.tsx +++ b/src/components/postOptionsModal/container/postOptionsModal.tsx @@ -228,7 +228,9 @@ const PostOptionsModal = ({ pageType }: Props, ref) => { buttons: [ { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {console.log("cancel pressed")}, + onPress: () => { + console.log('cancel pressed'); + }, }, { text: intl.formatMessage({ id: 'alert.confirm' }), diff --git a/src/components/qrModal/qrModalView.tsx b/src/components/qrModal/qrModalView.tsx index cf6a30f7d..f93973027 100644 --- a/src/components/qrModal/qrModalView.tsx +++ b/src/components/qrModal/qrModalView.tsx @@ -181,7 +181,9 @@ export const QRModal = ({}: QRModalProps) => { text: intl.formatMessage({ id: 'qr.cancel', }), - onPress: () => {console.log("cancel pressed")}, + onPress: () => { + console.log('cancel pressed'); + }, style: 'cancel', }, { diff --git a/src/components/sideMenu/view/sideMenuView.js b/src/components/sideMenu/view/sideMenuView.js index d2393cd08..ed4042448 100644 --- a/src/components/sideMenu/view/sideMenuView.js +++ b/src/components/sideMenu/view/sideMenuView.js @@ -78,7 +78,9 @@ const SideMenuView = ({ buttons: [ { text: intl.formatMessage({ id: 'side_menu.cancel' }), - onPress: () => {console.log("cancel pressed")}, + onPress: () => { + console.log('cancel pressed'); + }, }, { text: intl.formatMessage({ id: 'side_menu.logout' }), diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 225136453..f2b5c99e9 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -332,7 +332,9 @@ export const UploadsGalleryModal = forwardRef( let body = error.message || JSON.stringify(error); let action: AlertButton = { text: intl.formatMessage({ id: 'alert.okay' }), - onPress: () => {console.log("cancel pressed")}, + onPress: () => { + console.log('cancel pressed'); + }, }; switch (error.code) { diff --git a/src/containers/profileContainer.js b/src/containers/profileContainer.js index 7a3b19f94..a270b6b99 100644 --- a/src/containers/profileContainer.js +++ b/src/containers/profileContainer.js @@ -428,7 +428,9 @@ class ProfileContainer extends Component { buttons: [ { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {console.log("cancel pressed")}, + onPress: () => { + console.log('cancel pressed'); + }, }, { text: intl.formatMessage({ id: 'alert.confirm' }), diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index af72c0eb8..ab0c98925 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -1165,7 +1165,9 @@ class EditorContainer extends Component { handleShouldReblogChange={this._handleShouldReblogChange} handleSchedulePress={this._handleSchedulePress} handleFormChanged={this._handleFormChanged} - handleOnBackPress={() => {console.log("cancel pressed")}} + handleOnBackPress={() => { + console.log('cancel pressed'); + }} handleOnSubmit={this._handleSubmit} initialEditor={this._initialEditor} isDarkTheme={isDarkTheme} diff --git a/src/screens/editor/screen/editorScreen.tsx b/src/screens/editor/screen/editorScreen.tsx index 6a4219ebe..6d56c3011 100644 --- a/src/screens/editor/screen/editorScreen.tsx +++ b/src/screens/editor/screen/editorScreen.tsx @@ -181,7 +181,9 @@ class EditorScreen extends Component { }, { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {console.log("cancel pressed")}, + onPress: () => { + console.log('cancel pressed'); + }, style: 'cancel', }, ]); diff --git a/src/screens/settings/container/settingsContainer.tsx b/src/screens/settings/container/settingsContainer.tsx index 051e325e0..88370fe6a 100644 --- a/src/screens/settings/container/settingsContainer.tsx +++ b/src/screens/settings/container/settingsContainer.tsx @@ -320,7 +320,9 @@ class SettingsContainer extends Component { buttons: [ { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {console.log("cancel pressed")}, + onPress: () => { + console.log('cancel pressed'); + }, type: 'destructive', }, { @@ -458,7 +460,9 @@ class SettingsContainer extends Component { buttons: [ { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {console.log("cancel pressed")}, + onPress: () => { + console.log('cancel pressed'); + }, }, { text: intl.formatMessage({ id: 'alert.delete' }), diff --git a/src/screens/trade/children/swapTokenContent.tsx b/src/screens/trade/children/swapTokenContent.tsx index cf06e2758..e53ab384b 100644 --- a/src/screens/trade/children/swapTokenContent.tsx +++ b/src/screens/trade/children/swapTokenContent.tsx @@ -211,7 +211,12 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }: }, ), buttons: [ - { textId: 'alert.cancel', onPress: () => {console.log("cancel pressed")} }, + { + textId: 'alert.cancel', + onPress: () => { + console.log('cancel pressed'); + }, + }, { textId: 'alert.confirm', onPress: _confirmSwap }, ], }), diff --git a/src/screens/transfer/screen/transferScreen.js b/src/screens/transfer/screen/transferScreen.js index e95b85c78..7125306b1 100644 --- a/src/screens/transfer/screen/transferScreen.js +++ b/src/screens/transfer/screen/transferScreen.js @@ -247,7 +247,9 @@ const TransferView = ({ buttons: [ { text: intl.formatMessage({ id: 'alert.cancel' }), - onPress: () => {console.log("cancel pressed")}, + onPress: () => { + console.log('cancel pressed'); + }, }, { text: intl.formatMessage({ id: 'alert.confirm' }), diff --git a/src/screens/voters/screen/votersScreen.js b/src/screens/voters/screen/votersScreen.js index c6dc91e49..09e90a8e4 100644 --- a/src/screens/voters/screen/votersScreen.js +++ b/src/screens/voters/screen/votersScreen.js @@ -33,7 +33,9 @@ const VotersScreen = ({ route }) => { post.active_votes = parseActiveVotes({ ...post, active_votes: result }); setPost({ ...post }); }) - .catch(() => {console.log("cancel pressed")}); + .catch(() => { + console.log('cancel pressed'); + }); } }, [route.params?.content]); diff --git a/src/utils/crypto.js b/src/utils/crypto.js index 8922923c5..ddc07a968 100644 --- a/src/utils/crypto.js +++ b/src/utils/crypto.js @@ -57,7 +57,7 @@ const getStampedData = (data) => { }; const processStampedData = (stampedData) => { - if (stampedData.hasOwnProperty('stamp') && stampedData.stamp == STAMP) { + if (stampedData?.stamp && stampedData.stamp == STAMP) { return stampedData.data; } throw new Error('Possibly un-stamped legacy data'); diff --git a/src/utils/editor.ts b/src/utils/editor.ts index 43ce859bf..ad8703d49 100644 --- a/src/utils/editor.ts +++ b/src/utils/editor.ts @@ -36,7 +36,7 @@ export const generatePermlink = (title, random = false) => { if (perm.length > 255) { perm = perm.substring(perm.length - 255, perm.length); } - + // only letters numbers and dashes perm = perm.toLowerCase().replace(/[^a-z0-9-]+/g, ''); diff --git a/src/utils/hive-uri.ts b/src/utils/hive-uri.ts index 0ba36664b..2726bc50c 100644 --- a/src/utils/hive-uri.ts +++ b/src/utils/hive-uri.ts @@ -19,17 +19,16 @@ const _checkOpsArray = (ops: any) => { }; const findParentKey = (obj, value, parentKey = null) => { - - Object.keys(obj).forEach((key) => { - if (obj[key] === value) { - return parentKey; - } else if (typeof obj[key] === 'object') { - const foundKey = findParentKey(obj[key], value, key); - if (foundKey) { - return foundKey; - } + Object.keys(obj).forEach((key) => { + if (obj[key] === value) { + return parentKey; + } else if (typeof obj[key] === 'object') { + const foundKey = findParentKey(obj[key], value, key); + if (foundKey) { + return foundKey; } - }) + } + }); return null; }; @@ -105,7 +104,7 @@ export const getFormattedTx = (tx: any, authoritiesMap: Map) => return Promise.reject(errorObj); } // if amount field present in operation, validate and check for proper formatting and format to 3 decimal places - if (!!operationObj?.amount) { + if (operationObj?.amount) { const amount = _formatAmount(operationObj.amount); operationObj.amount = amount; if (!amount) { diff --git a/src/utils/migrationHelpers.ts b/src/utils/migrationHelpers.ts index 7e8ce712b..162594367 100644 --- a/src/utils/migrationHelpers.ts +++ b/src/utils/migrationHelpers.ts @@ -212,7 +212,9 @@ export const repairUserAccountData = async (username, dispatch, intl, accounts, { text: intl.formatMessage({ id: 'alert.cancel' }), style: 'destructive', - onPress: () => {console.log("cancel pressed")}, + onPress: () => { + console.log('cancel pressed'); + }, }, { text: intl.formatMessage({ id: 'alert.verify' }), diff --git a/src/utils/postParser.tsx b/src/utils/postParser.tsx index 4cdeb391d..fd28ad3cd 100644 --- a/src/utils/postParser.tsx +++ b/src/utils/postParser.tsx @@ -1,4 +1,3 @@ - import { get, isArray } from 'lodash'; import { Platform } from 'react-native'; import { postBodySummary, renderPostBody, catchPostImage } from '@ecency/render-helper'; @@ -94,7 +93,6 @@ export const parsePost = ( export const parseDiscussionCollection = async (commentsMap: { [key: string]: any }) => { Object.keys(commentsMap).forEach((key) => { - const comment = commentsMap[key]; // prcoess first level comment @@ -103,8 +101,7 @@ export const parseDiscussionCollection = async (commentsMap: { [key: string]: an } else { delete commentsMap[key]; } - - }) + }); console.log('parsed discussion collection', commentsMap); return commentsMap; @@ -137,7 +134,6 @@ export const parseCommentThreads = async (commentsMap: any, author: string, perm }; Object.keys(commentsMap).forEach((key) => { - const comment = commentsMap[key]; // prcoess first level comment @@ -146,8 +142,7 @@ export const parseCommentThreads = async (commentsMap: any, author: string, perm _parsedComment.replies = parseReplies(commentsMap, _parsedComment.replies, 1); comments.push(_parsedComment); } - - }) + }); return comments; }; @@ -188,7 +183,7 @@ export const mapDiscussionToThreads = async ( comment.replies = parseReplies(commentsMap, comment.replies, 1); comments.push(comment); } - }) + }); return comments; }; @@ -260,7 +255,7 @@ export const injectPostCache = (commentsMap, cachedComments, cachedVotes, lastCa console.log('injection vote cache'); _comments[path] = injectVoteCache(_comments[path], cachedVote); } - }) + }); // process comments cache @@ -307,7 +302,7 @@ export const injectPostCache = (commentsMap, cachedComments, cachedVotes, lastCa } break; } - }) + }); return shouldClone ? { ..._comments } : _comments; }; diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 73e5390e6..f7474206f 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -664,11 +664,7 @@ const fetchEngineTokensData = async ( return engineCoinData; }; -const _fetchSpkWalletData = async ( - username: string, - hivePrice: number, - vsCurrency: string, -) => { +const _fetchSpkWalletData = async (username: string, hivePrice: number, vsCurrency: string) => { const spkWalletData: { [key: string]: CoinData } = {}; try { From 081ef12919aac7567166eee7618821b30b287b78 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 16:07:38 +0500 Subject: [PATCH 040/111] introduced swap calculator to avoid namespace HiveMarket usage --- .../trade/children/swapCalculatorHelpers.ts | 88 +++++++++++++++++ .../trade/children/useSwapCalculator.tsx | 97 +------------------ 2 files changed, 92 insertions(+), 93 deletions(-) create mode 100644 src/screens/trade/children/swapCalculatorHelpers.ts diff --git a/src/screens/trade/children/swapCalculatorHelpers.ts b/src/screens/trade/children/swapCalculatorHelpers.ts new file mode 100644 index 000000000..2527ed2b4 --- /dev/null +++ b/src/screens/trade/children/swapCalculatorHelpers.ts @@ -0,0 +1,88 @@ +import { Alert } from 'react-native'; +import bugsnapInstance from '../../../config/bugsnag'; +import { MarketAsset, OrdersDataItem } from '../../../providers/hive-trade/hiveTrade.types'; +import { getOrderBook } from '../../../providers/hive/dhive'; + +interface ProcessingResult { + tooMuchSlippage?: boolean; + invalidAmount?: boolean; + toAmount?: number; + emptyOrderBook?: boolean; +} + +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) { + available += book[index][asset] / 1000; + index++; + } + return +book[index].real_price; +} + +export async function fetchHiveOrderBook() { + try { + return await getOrderBook(); + } catch (e) { + bugsnapInstance.notify(e); + Alert.alert('Order book is empty'); + } + return null; +} + +export function processHiveOrderBook( + buyOrderBook: OrdersDataItem[], + sellOrderBook: OrdersDataItem[], + fromAmount: number, + asset: string, +): ProcessingResult { + if (buyOrderBook.length <= 0 || sellOrderBook.length <= 0) return { emptyOrderBook: true }; + + let invalidAmount = false; + let availableInOrderBook, + price = 0; + let firstPrice = Infinity; + 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'); + 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'); + toAmount = fromAmount / price; + firstPrice = +sellOrderBook[0].real_price; + } + + if (!availableInOrderBook) return { emptyOrderBook: true }; + + const slippage = Math.abs(price - firstPrice); + const tooMuchSlippage = slippage > 0.01; + + if (fromAmount > availableInOrderBook) { + invalidAmount = true; + } else if (toAmount) { + resultToAmount = toAmount; + invalidAmount = false; + } + return { toAmount: resultToAmount, tooMuchSlippage, invalidAmount }; +} + +export async function getNewAmount(toAmount: string, fromAmount: number, asset: MarketAsset) { + const book = await fetchHiveOrderBook(); + const { toAmount: newToAmount } = processHiveOrderBook( + book?.bids ?? [], + book?.asks ?? [], + fromAmount, + asset, + ); + if (newToAmount) { + return newToAmount; + } + return toAmount; +} diff --git a/src/screens/trade/children/useSwapCalculator.tsx b/src/screens/trade/children/useSwapCalculator.tsx index b30f0d5a2..03cd828f8 100644 --- a/src/screens/trade/children/useSwapCalculator.tsx +++ b/src/screens/trade/children/useSwapCalculator.tsx @@ -1,96 +1,7 @@ -import React, { useEffect, useRef, useState } from 'react'; -import { Alert } from 'react-native'; +import { useEffect, useRef, useState } from 'react'; 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 { - tooMuchSlippage?: boolean; - invalidAmount?: boolean; - toAmount?: number; - emptyOrderBook?: boolean; - } - - 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) { - available += book[index][asset] / 1000; - index++; - } - return +book[index].real_price; - } - - export async function fetchHiveOrderBook() { - try { - return await getOrderBook(); - } catch (e) { - bugsnapInstance.notify(e); - Alert.alert('Order book is empty'); - } - return null; - } - - export function processHiveOrderBook( - buyOrderBook: OrdersDataItem[], - sellOrderBook: OrdersDataItem[], - fromAmount: number, - asset: string, - ): ProcessingResult { - if (buyOrderBook.length <= 0 || sellOrderBook.length <= 0) return { emptyOrderBook: true }; - - let tooMuchSlippage, - invalidAmount = false; - let availableInOrderBook, - price = 0; - let firstPrice = Infinity; - 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'); - 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'); - toAmount = fromAmount / price; - firstPrice = +sellOrderBook[0].real_price; - } - - if (!availableInOrderBook) return { emptyOrderBook: true }; - - const slippage = Math.abs(price - firstPrice); - tooMuchSlippage = slippage > 0.01; - - if (fromAmount > availableInOrderBook) { - invalidAmount = true; - } else if (toAmount) { - resultToAmount = toAmount; - invalidAmount = false; - } - return { toAmount: resultToAmount, tooMuchSlippage, invalidAmount }; - } - - export async function getNewAmount(toAmount: string, fromAmount: number, asset: MarketAsset) { - const book = await HiveMarket.fetchHiveOrderBook(); - const { toAmount: newToAmount } = HiveMarket.processHiveOrderBook( - book?.bids ?? [], - book?.asks ?? [], - fromAmount, - asset, - ); - if (newToAmount) { - return newToAmount; - } - return toAmount; - } -} +import { fetchHiveOrderBook, processHiveOrderBook } from './swapCalculatorHelpers'; export const useSwapCalculator = ( asset: MarketAsset, @@ -135,7 +46,7 @@ export const useSwapCalculator = ( tooMuchSlippage: _tooMuchSlippage, invalidAmount: _invalidAmount, toAmount: _toAmount, - } = HiveMarket.processHiveOrderBook(buyOrderBook, sellOrderBook, fromAmount, asset); + } = processHiveOrderBook(buyOrderBook, sellOrderBook, fromAmount, asset); setTooMuchSlippage(!!_tooMuchSlippage); setOfferUnavailable(!!_invalidAmount); if (_toAmount) { @@ -146,7 +57,7 @@ export const useSwapCalculator = ( const fetchOrderBook = async () => { setIsLoading(true); try { - const book = await HiveMarket.fetchHiveOrderBook(); + const book = await fetchHiveOrderBook(); if (book) { setBuyOrderBook(book.bids); setSellOrderBook(book.asks); From 17f14dccb749c3481109282a9e55d94a57fea85c Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 16:08:01 +0500 Subject: [PATCH 041/111] reduced errors below 200 --- src/screens/feed/screen/feedScreen.tsx | 2 +- .../login/container/loginContainer.tsx | 2 +- .../pinCode/container/pinCodeContainer.tsx | 101 +++++++++--------- .../best/container/postsResultsContainer.tsx | 10 +- .../container/communitiesResultsContainer.js | 2 +- .../settings/container/settingsContainer.tsx | 5 +- .../trade/children/swapAmountInput.tsx | 1 - .../trade/children/swapTokenContent.tsx | 2 +- src/screens/trade/screen/tradeScreen.tsx | 9 +- src/screens/wallet/children/assetCard.tsx | 2 +- src/screens/wallet/children/claimButton.tsx | 3 +- src/screens/wallet/screen/walletScreen.tsx | 2 +- src/screens/waves/children/wavesHeader.tsx | 4 +- src/utils/communitiesUtils.ts | 6 +- 14 files changed, 70 insertions(+), 81 deletions(-) diff --git a/src/screens/feed/screen/feedScreen.tsx b/src/screens/feed/screen/feedScreen.tsx index accc569a1..294b27b84 100644 --- a/src/screens/feed/screen/feedScreen.tsx +++ b/src/screens/feed/screen/feedScreen.tsx @@ -1,5 +1,5 @@ import React, { Fragment, useState } from 'react'; -import { View, Text } from 'react-native'; +import { View } from 'react-native'; import get from 'lodash/get'; // Components diff --git a/src/screens/login/container/loginContainer.tsx b/src/screens/login/container/loginContainer.tsx index cd3d117cf..f3bf48522 100644 --- a/src/screens/login/container/loginContainer.tsx +++ b/src/screens/login/container/loginContainer.tsx @@ -224,7 +224,7 @@ class LoginContainer extends PureComponent { }; const notifyTypes = []; - Object.keys(notificationDetails).map((item) => { + Object.keys(notificationDetails).forEach((item) => { const notificationType = item.replace('Notification', ''); if (notificationDetails[item]) { diff --git a/src/screens/pinCode/container/pinCodeContainer.tsx b/src/screens/pinCode/container/pinCodeContainer.tsx index 4d0de720e..6a6e5002b 100644 --- a/src/screens/pinCode/container/pinCodeContainer.tsx +++ b/src/screens/pinCode/container/pinCodeContainer.tsx @@ -130,7 +130,6 @@ class PinCodeContainer extends Component { _resetPinCode = (pin) => new Promise((resolve, reject) => { const { - dispatch, pinCodeParams: { navigateTo, navigateParams, navigateKey, callback }, encUnlockPin, intl, @@ -227,60 +226,56 @@ class PinCodeContainer extends Component { // verifies is the pin entered is right or wrong, also migrates to newer locking method _verifyPinCode = async (pin) => { - try { - const { - intl, - currentAccount, - dispatch, - encUnlockPin, - applicationPinCode, - pinCodeParams: { navigateTo, navigateParams, navigateKey, callback }, - navigation, - } = this.props; - const { oldPinCode } = this.state; + const { + intl, + currentAccount, + dispatch, + encUnlockPin, + applicationPinCode, + pinCodeParams: { navigateTo, navigateParams, navigateKey, callback }, + navigation, + } = this.props; + const { oldPinCode } = this.state; - const unlockPin = encUnlockPin - ? decryptKey(encUnlockPin, Config.PIN_KEY) - : decryptKey(applicationPinCode, Config.PIN_KEY); + const unlockPin = encUnlockPin + ? decryptKey(encUnlockPin, Config.PIN_KEY) + : decryptKey(applicationPinCode, Config.PIN_KEY); - // check if pins match - if (unlockPin !== pin) { - throw new Error( - intl.formatMessage({ - id: 'alert.invalid_pincode', - }), - ); - } - - // migrate data to default pin if encUnlockPin is not set. - if (!encUnlockPin) { - await MigrationHelpers.migrateUserEncryption( - dispatch, - currentAccount, - applicationPinCode, - this._onRefreshTokenFailed, - ); - } - - // on successful code verification run requested operation passed as props - if (callback) { - callback(pin, oldPinCode); - } - - if (navigateTo) { - RootNavigation.navigate({ - name: navigateTo, - params: navigateParams, - key: navigateKey || '', - }); - } else { - navigation.goBack(); - } - - return true; - } catch (err) { - throw err; + // check if pins match + if (unlockPin !== pin) { + throw new Error( + intl.formatMessage({ + id: 'alert.invalid_pincode', + }), + ); } + + // migrate data to default pin if encUnlockPin is not set. + if (!encUnlockPin) { + await MigrationHelpers.migrateUserEncryption( + dispatch, + currentAccount, + applicationPinCode, + this._onRefreshTokenFailed, + ); + } + + // on successful code verification run requested operation passed as props + if (callback) { + callback(pin, oldPinCode); + } + + if (navigateTo) { + RootNavigation.navigate({ + name: navigateTo, + params: navigateParams, + key: navigateKey || '', + }); + } else { + navigation.goBack(); + } + + return true; }; // encryptes and saved unlockPin @@ -291,7 +286,7 @@ class PinCodeContainer extends Component { }; _forgotPinCode = async () => { - const { otherAccounts, dispatch, navigation } = this.props; + const { otherAccounts, dispatch } = this.props; await removeAllUserData() .then(async () => { diff --git a/src/screens/searchResult/screen/tabs/best/container/postsResultsContainer.tsx b/src/screens/searchResult/screen/tabs/best/container/postsResultsContainer.tsx index aab72cb95..735ed3af0 100644 --- a/src/screens/searchResult/screen/tabs/best/container/postsResultsContainer.tsx +++ b/src/screens/searchResult/screen/tabs/best/container/postsResultsContainer.tsx @@ -15,7 +15,7 @@ const PostsResultsContainer = ({ children, searchValue }) => { const postsCacherPrimer = postQueries.usePostsCachePrimer(); const [data, setData] = useState([]); - const [sort, setSort] = useState('newest'); + const [sort] = useState('newest'); const [scrollId, setScrollId] = useState(''); const [noResult, setNoResult] = useState(false); @@ -39,7 +39,7 @@ const PostsResultsContainer = ({ children, searchValue }) => { setData([]); } }) - .catch((err) => { + .catch(() => { setNoResult(true); setData([]); }); @@ -56,7 +56,7 @@ const PostsResultsContainer = ({ children, searchValue }) => { setData([]); } }) - .catch((err) => { + .catch(() => { setNoResult(true); setData([]); }); @@ -71,7 +71,7 @@ const PostsResultsContainer = ({ children, searchValue }) => { sort: 'blog', }; - return await getAccountPosts(options); + return getAccountPosts(options); }; // Component Functions @@ -88,7 +88,7 @@ const PostsResultsContainer = ({ children, searchValue }) => { }); }; - const _loadMore = (index, value) => { + const _loadMore = () => { if (scrollId && searchValue) { search({ q: `${searchValue} type:post`, sort, scroll_id: scrollId }) .then((res) => { diff --git a/src/screens/searchResult/screen/tabs/communities/container/communitiesResultsContainer.js b/src/screens/searchResult/screen/tabs/communities/container/communitiesResultsContainer.js index 31a17ca20..53e1c262c 100644 --- a/src/screens/searchResult/screen/tabs/communities/container/communitiesResultsContainer.js +++ b/src/screens/searchResult/screen/tabs/communities/container/communitiesResultsContainer.js @@ -97,7 +97,7 @@ const CommunitiesResultsContainer = ({ children, searchValue }) => { useEffect(() => { const communitiesData = [...data]; - Object.keys(subscribingCommunities).map((communityId) => { + Object.keys(subscribingCommunities).forEach((communityId) => { if (!subscribingCommunities[communityId].loading) { if (!subscribingCommunities[communityId].error) { if (subscribingCommunities[communityId].isSubscribed) { diff --git a/src/screens/settings/container/settingsContainer.tsx b/src/screens/settings/container/settingsContainer.tsx index 88370fe6a..5286ab6d6 100644 --- a/src/screens/settings/container/settingsContainer.tsx +++ b/src/screens/settings/container/settingsContainer.tsx @@ -274,7 +274,7 @@ class SettingsContainer extends Component { type: actionType, }); - Object.keys(notificationDetails).map((item) => { + Object.keys(notificationDetails).forEach((item) => { const notificationType = item.replace('Notification', ''); if (notificationType === actionType.replace('notification.', '')) { @@ -530,8 +530,7 @@ class SettingsContainer extends Component { }; render() { - const { serverList, isNotificationMenuOpen, isLoading, isVisibleBackupKeysModal } = this - .state as any; + const { serverList, isNotificationMenuOpen, isLoading } = this.state as any; const { colorTheme } = this.props as any; return ( diff --git a/src/screens/trade/children/swapAmountInput.tsx b/src/screens/trade/children/swapAmountInput.tsx index 677b55565..0184b922a 100644 --- a/src/screens/trade/children/swapAmountInput.tsx +++ b/src/screens/trade/children/swapAmountInput.tsx @@ -10,7 +10,6 @@ interface SwapInputProps { value: string; fiatPrice: number; symbol: string; - disabled?: boolean; } // Reusable component for label, text input, and bottom text diff --git a/src/screens/trade/children/swapTokenContent.tsx b/src/screens/trade/children/swapTokenContent.tsx index e53ab384b..4feb83771 100644 --- a/src/screens/trade/children/swapTokenContent.tsx +++ b/src/screens/trade/children/swapTokenContent.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useMemo, useRef, useState } from 'react'; +import React, { useEffect, useMemo, useState } from 'react'; import { View, Text, Alert, RefreshControl } from 'react-native'; import { useIntl } from 'react-intl'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; diff --git a/src/screens/trade/screen/tradeScreen.tsx b/src/screens/trade/screen/tradeScreen.tsx index 992d1e220..4c9c8d352 100644 --- a/src/screens/trade/screen/tradeScreen.tsx +++ b/src/screens/trade/screen/tradeScreen.tsx @@ -1,14 +1,13 @@ import React, { useState } from 'react'; -import { View } from 'react-native'; import { useIntl } from 'react-intl'; +import { View } from 'react-native'; import WebView from 'react-native-webview'; -import { useDispatch } from 'react-redux'; -import styles from '../styles/tradeScreen.styles'; -import { SwapTokenContent } from '../children'; import { BasicHeader, Modal } from '../../../components'; +import { SwapTokenContent } from '../children'; +import styles from '../styles/tradeScreen.styles'; -import TransferTypes from '../../../constants/transferTypes'; import { hsOptions } from '../../../constants/hsOptions'; +import TransferTypes from '../../../constants/transferTypes'; import { walletQueries } from '../../../providers/queries'; import { delay } from '../../../utils/editor'; diff --git a/src/screens/wallet/children/assetCard.tsx b/src/screens/wallet/children/assetCard.tsx index f65322b80..76423f242 100644 --- a/src/screens/wallet/children/assetCard.tsx +++ b/src/screens/wallet/children/assetCard.tsx @@ -1,5 +1,5 @@ import { View, Text, TouchableOpacity, Alert } from 'react-native'; -import React, { ComponentType, useEffect, useState } from 'react'; +import React, { ComponentType } from 'react'; import { useIntl } from 'react-intl'; import EStyleSheet from 'react-native-extended-stylesheet'; import styles from '../styles/children.styles'; diff --git a/src/screens/wallet/children/claimButton.tsx b/src/screens/wallet/children/claimButton.tsx index afc491718..6900bc8c6 100644 --- a/src/screens/wallet/children/claimButton.tsx +++ b/src/screens/wallet/children/claimButton.tsx @@ -1,5 +1,5 @@ import React, { Fragment } from 'react'; -import { View, Text, ActivityIndicator, ViewStyle } from 'react-native'; +import { View, Text, ViewStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; import { MainButton, Icon } from '../../../components'; import styles from '../styles/claimButton.styles'; @@ -8,7 +8,6 @@ interface ClaimButtonProps { title: string; isLoading?: boolean; isClaiming?: boolean; - isClaimExpected?: boolean; isDisabled?: boolean; containerStyle: ViewStyle; onPress: () => void; diff --git a/src/screens/wallet/screen/walletScreen.tsx b/src/screens/wallet/screen/walletScreen.tsx index d2f58e039..f80cf95d1 100644 --- a/src/screens/wallet/screen/walletScreen.tsx +++ b/src/screens/wallet/screen/walletScreen.tsx @@ -18,7 +18,7 @@ import styles from './walletScreenStyles'; import { useAppDispatch, useAppSelector } from '../../../hooks'; import { AssetCard, ManageAssetsBtn } from '../children'; -import { ChartInterval, fetchMarketChart } from '../../../providers/coingecko/coingecko'; +import { fetchMarketChart } from '../../../providers/coingecko/coingecko'; import ROUTES from '../../../constants/routeNames'; import { AssetDetailsScreenParams } from '../../assetDetails/screen/assetDetailsScreen'; import POINTS, { POINTS_KEYS } from '../../../constants/options/points'; diff --git a/src/screens/waves/children/wavesHeader.tsx b/src/screens/waves/children/wavesHeader.tsx index aa25556f4..d6411b81b 100644 --- a/src/screens/waves/children/wavesHeader.tsx +++ b/src/screens/waves/children/wavesHeader.tsx @@ -6,9 +6,7 @@ import { WritePostButton } from '../../../components/atoms'; import { showReplyModal } from '../../../redux/actions/uiAction'; import styles from '../styles/children.styles'; -interface WavesHeaderProps {} - -export const WavesHeader: React.FC = ({}) => { +export const WavesHeader = () => { const dispatch = useDispatch(); const intl = useIntl(); diff --git a/src/utils/communitiesUtils.ts b/src/utils/communitiesUtils.ts index 10fcdec91..02a308335 100644 --- a/src/utils/communitiesUtils.ts +++ b/src/utils/communitiesUtils.ts @@ -13,8 +13,8 @@ export const mergeSubCommunitiesCacheInSubList = ( if (!cacheMap || !cacheMap.size) { return subList.sort((a, b) => a[1].localeCompare(b[1])); } - const cacheList = Array.from(cacheMap, ([path, item]) => item.data); - cacheList.map((cacheListItem) => { + const cacheList = Array.from(cacheMap, ([, item]) => item.data); + cacheList.forEach((cacheListItem) => { const index = subList.findIndex((subListItem) => subListItem[0] === cacheListItem[0]); if (index !== -1) { subList[index] = [...cacheListItem]; @@ -40,7 +40,7 @@ export const mergeSubCommunitiesCacheInDiscoverList = ( discoverList.forEach((discoverListItem) => { const itemExist = cacheMap.get(discoverListItem.name); if (itemExist) { - discoverListItem.isSubscribed = itemExist.data[4]; + [, , , , discoverListItem.isSubscribed] = itemExist.data; } }); return discoverList; From 0b94245b53e8d0744aac19f67bb799ab5793bb13 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 16:16:59 +0500 Subject: [PATCH 042/111] mime-type fix --- package.json | 1 + yarn.lock | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index d3f5d1824..e6c8e4181 100644 --- a/package.json +++ b/package.json @@ -89,6 +89,7 @@ "lodash": "^4.17.13", "lottie-ios": "3.4.0", "lottie-react-native": "^5.1.3", + "mime-types": "^2.1.35", "moment": "^2.29.2", "path-browserify": "0.0.0", "process": "^0.11.0", diff --git a/yarn.lock b/yarn.lock index 6963221f5..5886f0383 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7714,7 +7714,7 @@ mime-db@1.52.0, "mime-db@>= 1.43.0 < 2": resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg== -mime-types@^2.1.12, mime-types@^2.1.27, mime-types@~2.1.34: +mime-types@^2.1.12, mime-types@^2.1.27, mime-types@^2.1.35, mime-types@~2.1.34: version "2.1.35" resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a" integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw== From 427d4a8305bcc2a0562da2dd8b1c4a9a78245147 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 16:36:22 +0500 Subject: [PATCH 043/111] lint errors below 150 --- .../accountsBottomSheetContainer.tsx | 19 +++---- .../container/actionModalContainer.tsx | 2 +- .../actionModal/view/actionModalStyles.ts | 2 +- .../autoHeightImage/autoHeightImage.tsx | 4 +- .../beneficiaryModal/beneficiaryModal.tsx | 6 +-- .../beneficiarySelectionContent.tsx | 19 +++---- .../bottomTabBar/view/bottomTabBarView.tsx | 2 +- .../view/collapsibleCardView.js | 2 +- .../comments/container/commentsContainer.tsx | 13 ----- .../communitiesList/view/communitiesList.js | 3 +- .../customiseFiltersModal.tsx | 50 +++++++++---------- .../customiseFiltersModalStyles.ts | 2 +- .../draftListItem/view/draftListItemView.tsx | 1 - src/providers/hive-engine/hiveEngine.ts | 1 + src/providers/hive-spk/hiveSpk.ts | 24 ++++----- src/providers/hive-trade/hiveTrade.ts | 4 +- src/providers/hive/auth.js | 4 +- .../queries/postQueries/postQueries.ts | 2 +- src/redux/reducers/applicationReducer.ts | 2 - .../container/applicationContainer.tsx | 3 +- .../backupKeysScreen/backupKeysScreen.tsx | 10 ---- .../importPrivateKeyModal.tsx | 4 +- .../container/communitiesContainer.js | 6 +-- .../community/screen/communityScreen.js | 2 +- .../editor/children/postOptionsModal.tsx | 2 +- src/screens/editor/screen/editorScreen.tsx | 5 +- 26 files changed, 77 insertions(+), 117 deletions(-) diff --git a/src/components/accountsBottomSheet/container/accountsBottomSheetContainer.tsx b/src/components/accountsBottomSheet/container/accountsBottomSheetContainer.tsx index a33206a1b..d86ad6e10 100644 --- a/src/components/accountsBottomSheet/container/accountsBottomSheetContainer.tsx +++ b/src/components/accountsBottomSheet/container/accountsBottomSheetContainer.tsx @@ -1,37 +1,32 @@ import React, { useEffect, useRef } from 'react'; import { useDispatch } from 'react-redux'; -import { Alert } from 'react-native'; import { useIntl } from 'react-intl'; +import { Alert } from 'react-native'; import RootNavigation from '../../../navigation/rootNavigation'; import { updateCurrentAccount } from '../../../redux/actions/accountAction'; -import { getUserDataWithUsername } from '../../../realm/realm'; import { migrateToMasterKeyWithAccessToken, refreshSCToken, switchAccount, } from '../../../providers/hive/auth'; +import { getUserDataWithUsername } from '../../../realm/realm'; +import { logout, toggleAccountsBottomSheet } from '../../../redux/actions/uiAction'; import AccountsBottomSheet from '../view/accountsBottomSheetView'; -import { - logout, - showActionModal, - toggleAccountsBottomSheet, -} from '../../../redux/actions/uiAction'; // Constants import AUTH_TYPE from '../../../constants/authType'; import { getDigitPinCode, getMutes } from '../../../providers/hive/dhive'; import { useAppSelector } from '../../../hooks'; -import { getUnreadNotificationCount } from '../../../providers/ecency/ecency'; -import { decryptKey } from '../../../utils/crypto'; import { getPointsSummary } from '../../../providers/ecency/ePoint'; -import { fetchSubscribedCommunities } from '../../../redux/actions/communitiesAction'; +import { getUnreadNotificationCount } from '../../../providers/ecency/ecency'; import { clearSubscribedCommunitiesCache } from '../../../redux/actions/cacheActions'; -import ROUTES from '../../../constants/routeNames'; +import { fetchSubscribedCommunities } from '../../../redux/actions/communitiesAction'; +import { decryptKey } from '../../../utils/crypto'; import { repairUserAccountData } from '../../../utils/migrationHelpers'; const AccountsBottomSheetContainer = () => { @@ -108,7 +103,7 @@ const AccountsBottomSheetContainer = () => { } } - _currentAccount.local = realmData[0]; + [_currentAccount.local] = realmData; // migreate account to use access token for master key auth type if (realmData[0].authType !== AUTH_TYPE.STEEM_CONNECT && realmData[0].accessToken === '') { diff --git a/src/components/actionModal/container/actionModalContainer.tsx b/src/components/actionModal/container/actionModalContainer.tsx index c428e0165..f6c0ace66 100644 --- a/src/components/actionModal/container/actionModalContainer.tsx +++ b/src/components/actionModal/container/actionModalContainer.tsx @@ -20,7 +20,7 @@ export interface ActionModalData { bodyContent?: React.ReactNode; } -const ActionModalContainer = ({ navigation }) => { +const ActionModalContainer = () => { const dispatch = useDispatch(); const actionModalRef = useRef(); diff --git a/src/components/actionModal/view/actionModalStyles.ts b/src/components/actionModal/view/actionModalStyles.ts index 03b899056..b39dcd37c 100644 --- a/src/components/actionModal/view/actionModalStyles.ts +++ b/src/components/actionModal/view/actionModalStyles.ts @@ -1,4 +1,4 @@ -import { TextStyle, StyleSheet, ViewStyle, ImageStyle } from 'react-native'; +import { TextStyle, ViewStyle, ImageStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ diff --git a/src/components/autoHeightImage/autoHeightImage.tsx b/src/components/autoHeightImage/autoHeightImage.tsx index 34104fde9..0704e390c 100644 --- a/src/components/autoHeightImage/autoHeightImage.tsx +++ b/src/components/autoHeightImage/autoHeightImage.tsx @@ -1,6 +1,6 @@ import { proxifyImageSrc } from '@ecency/render-helper'; -import React, { useEffect, useMemo, useState } from 'react'; -import { Image, Platform, TouchableOpacity } from 'react-native'; +import React, { useMemo, useState } from 'react'; +import { Platform, TouchableOpacity } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; import FastImage from 'react-native-fast-image'; diff --git a/src/components/beneficiaryModal/beneficiaryModal.tsx b/src/components/beneficiaryModal/beneficiaryModal.tsx index 09c86da67..d1a1aab44 100644 --- a/src/components/beneficiaryModal/beneficiaryModal.tsx +++ b/src/components/beneficiaryModal/beneficiaryModal.tsx @@ -82,7 +82,7 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { const _onWeightInputChange = (value) => { const _value = (parseInt(value, 10) || 0) * 100; const _diff = _value - newWeight; - beneficiaries[0].weight = beneficiaries[0].weight - _diff; + beneficiaries[0].weight -= _diff; setNewWeight(_value); setIsWeightValid(_value > 0 && _value <= 10000); setBeneficiaries([...beneficiaries]); @@ -128,7 +128,7 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { const _renderInput = () => { const _onCancelPress = () => { if (newWeight) { - beneficiaries[0].weight = beneficiaries[0].weight + newWeight; + beneficiaries[0].weight += newWeight; setBeneficiaries([...beneficiaries]); setNewWeight(0); } @@ -206,7 +206,7 @@ const BeneficiaryModal = ({ username, handleOnSaveBeneficiaries, draftId }) => { const _isCurrentUser = item.account === username; const _onRemovePress = () => { - beneficiaries[0].weight = beneficiaries[0].weight + item.weight; + beneficiaries[0].weight += item.weight; beneficiaries.splice(index, 1); setBeneficiaries([...beneficiaries]); }; diff --git a/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx b/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx index 31ea8bb6e..dc9d41fff 100644 --- a/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx +++ b/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx @@ -1,20 +1,17 @@ -import React, { useState, useEffect } from 'react'; -import { View, FlatList, Text, TouchableOpacity } from 'react-native'; +import { debounce, isArray } from 'lodash'; +import React, { useEffect, useState } from 'react'; import { useIntl } from 'react-intl'; -import { isArray, debounce } from 'lodash'; +import { FlatList, Text, View } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; import styles from './styles'; +import { CheckBox, FormInput, IconButton, TextButton } from '..'; import { useAppDispatch, useAppSelector } from '../../hooks'; -import { BeneficiaryModal, CheckBox, FormInput, IconButton, TextButton } from '..'; -import { Beneficiary } from '../../redux/reducers/editorReducer'; import { lookupAccounts } from '../../providers/hive/dhive'; +import { setBeneficiaries as setBeneficiariesAction } from '../../redux/actions/editorActions'; import { TEMP_BENEFICIARIES_ID } from '../../redux/constants/constants'; -import { - removeBeneficiaries, - setBeneficiaries as setBeneficiariesAction, -} from '../../redux/actions/editorActions'; +import { Beneficiary } from '../../redux/reducers/editorReducer'; interface BeneficiarySelectionContentProps { draftId: string; @@ -178,7 +175,7 @@ const BeneficiarySelectionContent = ({ const _resetInputs = (adjustWeight = true) => { if (newWeight && adjustWeight) { - beneficiaries[0].weight = beneficiaries[0].weight + newWeight; + beneficiaries[0].weight += newWeight; setBeneficiaries([...beneficiaries]); } @@ -313,7 +310,7 @@ const BeneficiarySelectionContent = ({ const _isCurrentUser = item.account === username; const _onRemovePress = () => { - beneficiaries[0].weight = beneficiaries[0].weight + item.weight; + beneficiaries[0].weight += item.weight; const removedBeneficiary = beneficiaries.splice(index, 1); setBeneficiaries([...beneficiaries]); if (handleRemoveBeneficiary) { diff --git a/src/components/bottomTabBar/view/bottomTabBarView.tsx b/src/components/bottomTabBar/view/bottomTabBarView.tsx index b470aa61d..45bab50c1 100644 --- a/src/components/bottomTabBar/view/bottomTabBarView.tsx +++ b/src/components/bottomTabBar/view/bottomTabBarView.tsx @@ -1,5 +1,5 @@ import React, { useEffect } from 'react'; -import { SafeAreaView, View, TouchableOpacity, Alert } from 'react-native'; +import { SafeAreaView, View, TouchableOpacity } from 'react-native'; // Components // import TabBar from './tabbar'; diff --git a/src/components/collapsibleCard/view/collapsibleCardView.js b/src/components/collapsibleCard/view/collapsibleCardView.js index 17106c860..0e8141139 100644 --- a/src/components/collapsibleCard/view/collapsibleCardView.js +++ b/src/components/collapsibleCard/view/collapsibleCardView.js @@ -41,7 +41,7 @@ const CollapsibleCardView = (props) => { const [contentHeight, setContentHeight] = useState(0); useEffect(() => { - if (props.hasOwnProperty('isExpanded') && contentHeight) { + if (props?.isExpanded && contentHeight) { animation.value = { height: !isExpanded ? 0 : contentHeight + (moreHeight || 0) }; setCollapsed(isExpanded); } diff --git a/src/components/comments/container/commentsContainer.tsx b/src/components/comments/container/commentsContainer.tsx index 1aa10eacf..8be3ee209 100644 --- a/src/components/comments/container/commentsContainer.tsx +++ b/src/components/comments/container/commentsContainer.tsx @@ -178,18 +178,6 @@ const CommentsContainer = ({ } }; - const _handleOnReplyPress = (item) => { - navigation.navigate({ - name: ROUTES.SCREENS.EDITOR, - key: 'editor_reply', - params: { - isReply: true, - post: item, - fetchPost, - }, - }); - }; - const _handleOnVotersPress = (activeVotes, content) => { navigation.navigate({ name: ROUTES.SCREENS.VOTERS, @@ -256,7 +244,6 @@ const CommentsContainer = ({ postsCachePrimer.cachePost(comment); navigation.navigate({ name: ROUTES.SCREENS.POST, - key: comment.permlink, params: { author: comment.author, permlink: comment.permlink, diff --git a/src/components/communitiesList/view/communitiesList.js b/src/components/communitiesList/view/communitiesList.js index 44a0671a7..1e81bc3f2 100644 --- a/src/components/communitiesList/view/communitiesList.js +++ b/src/components/communitiesList/view/communitiesList.js @@ -36,7 +36,8 @@ const CommunitiesList = ({ isSubscribed={item.isSubscribed} isLoggedIn={isLoggedIn} loading={ - subscribingCommunities.hasOwnProperty(item.name) && + subscribingCommunities && + subscribingCommunities[item.name] && subscribingCommunities[item.name].loading } screen={screen} diff --git a/src/components/customiseFiltersModal/customiseFiltersModal.tsx b/src/components/customiseFiltersModal/customiseFiltersModal.tsx index 315fab817..c2457fa40 100644 --- a/src/components/customiseFiltersModal/customiseFiltersModal.tsx +++ b/src/components/customiseFiltersModal/customiseFiltersModal.tsx @@ -107,34 +107,32 @@ const CustomiseFiltersModal = ({ pageType }: Props, ref: Ref { const options = []; - for (const key in filterMap) { - if (filterMap.hasOwnProperty(key)) { - const isSelected = selectedFilters.has(key); + Object.keys(filterMap).forEach((key) => { + const isSelected = selectedFilters.has(key); - const _onPress = () => { - if (isSelected) { - selectedFilters.delete(key); - } else { - const index = getFilterIndex(filterMap, key); - selectedFilters.set(key, index); - } - setSelectedFilters(new Map([...selectedFilters])); - }; + const _onPress = () => { + if (isSelected) { + selectedFilters.delete(key); + } else { + const index = getFilterIndex(filterMap, key); + selectedFilters.set(key, index); + } + setSelectedFilters(new Map([...selectedFilters])); + }; - options.push( - - - - {intl.formatMessage({ - id: filterMap[key], - })} - - - - , - ); - } - } + options.push( + + + + {intl.formatMessage({ + id: filterMap[key], + })} + + + + , + ); + }); return {options}; }; diff --git a/src/components/customiseFiltersModal/customiseFiltersModalStyles.ts b/src/components/customiseFiltersModal/customiseFiltersModalStyles.ts index 5c7750023..e813f61ed 100644 --- a/src/components/customiseFiltersModal/customiseFiltersModalStyles.ts +++ b/src/components/customiseFiltersModal/customiseFiltersModalStyles.ts @@ -1,4 +1,4 @@ -import { TextStyle, StyleSheet, ViewStyle, ImageStyle } from 'react-native'; +import { TextStyle, ViewStyle, ImageStyle } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; import getWindowDimensions from '../../utils/getWindowDimensions'; diff --git a/src/components/draftListItem/view/draftListItemView.tsx b/src/components/draftListItem/view/draftListItemView.tsx index 1200b8406..a2e52a41a 100644 --- a/src/components/draftListItem/view/draftListItemView.tsx +++ b/src/components/draftListItem/view/draftListItemView.tsx @@ -26,7 +26,6 @@ const DraftListItemView = ({ reputation, created, image, - thumbnail, handleOnPressItem, handleOnRemoveItem, handleOnMovePress, diff --git a/src/providers/hive-engine/hiveEngine.ts b/src/providers/hive-engine/hiveEngine.ts index c78a0cc05..efb198f2d 100644 --- a/src/providers/hive-engine/hiveEngine.ts +++ b/src/providers/hive-engine/hiveEngine.ts @@ -176,6 +176,7 @@ export const fetchEngineMarketData = async ( } const data: MarketData[] = rawData.map(convertMarketData); + console.log('TODO: later use vsCurrency as well', vsCurrency); return days > 1 && data.length > days ? data.slice(data.length - days) : data; } catch (err) { diff --git a/src/providers/hive-spk/hiveSpk.ts b/src/providers/hive-spk/hiveSpk.ts index e5a76dd39..722d2e463 100644 --- a/src/providers/hive-spk/hiveSpk.ts +++ b/src/providers/hive-spk/hiveSpk.ts @@ -1,7 +1,6 @@ import { PrivateKey } from '@esteemapp/dhive'; import { Operation } from '@hiveio/dhive'; import axios from 'axios'; -import parseAsset from '../../utils/parseAsset'; import parseToken from '../../utils/parseToken'; import TransferTypes from '../../constants/transferTypes'; import { getActiveKey, getDigitPinCode, sendHiveOperations } from '../hive/dhive'; @@ -20,13 +19,14 @@ import { } from './hiveSpk.types'; export const SPK_NODE_ECENCY = 'good-karma.spk'; -const spkNodes = [ - 'https://spk.good-karma.xyz', - 'https://spkinstant.hivehoneycomb.com', - 'https://spknode.blocktrades.us', - 'https://spk.tcmd-spkcc.com', - 'https://spktoken.dlux.io', -]; + +// const spkNodes = [ +// 'https://spk.good-karma.xyz', +// 'https://spkinstant.hivehoneycomb.com', +// 'https://spknode.blocktrades.us', +// 'https://spk.tcmd-spkcc.com', +// 'https://spktoken.dlux.io', +// ]; const spkNode = 'https://spk.good-karma.xyz/'; // spkNodes[Math.floor(Math.random()*spkNodes.length)]; @@ -35,12 +35,12 @@ const spkApi = axios.create({ }); export function rewardSpk(data: SpkApiWallet, sstats: any) { - let r = 0, - a = 0, + let a = 0, b = 0, c = 0, - t = 0, - diff = data.head_block - data.spk_block; + t = 0; + + const diff = data.head_block - data.spk_block; if (!data.spk_block) { return 0; } else if (diff < 28800) { diff --git a/src/providers/hive-trade/hiveTrade.ts b/src/providers/hive-trade/hiveTrade.ts index 46a6bbeda..42780fbba 100644 --- a/src/providers/hive-trade/hiveTrade.ts +++ b/src/providers/hive-trade/hiveTrade.ts @@ -39,7 +39,7 @@ export const limitOrderCreate = ( let expiration: any = new Date(Date.now()); expiration.setDate(expiration.getDate() + 27); - expiration = expiration.toISOString().split('.')[0]; + [expiration] = expiration.toISOString().split('.'); const data = getLimitOrderCreateOpData( currentAccount.username, @@ -184,7 +184,7 @@ export const fetchHiveMarketRate = async (asset: MarketAsset): Promise = const getLimitOrderCreateOpData = (username, amountToSell, minToReceive, orderType, idPrefix) => { let expiration: any = new Date(Date.now()); expiration.setDate(expiration.getDate() + 27); - expiration = expiration.toISOString().split('.')[0]; + [expiration] = expiration.toISOString().split('.'); return { owner: username, diff --git a/src/providers/hive/auth.js b/src/providers/hive/auth.js index 1f1637a2a..44422b256 100644 --- a/src/providers/hive/auth.js +++ b/src/providers/hive/auth.js @@ -52,7 +52,7 @@ export const login = async (username, password) => { const privateKeys = getPrivateKeys(username, password); // Check all keys - Object.keys(publicKeys).map((pubKey) => { + Object.keys(publicKeys).forEach((pubKey) => { if (publicKeys[pubKey] === privateKeys[pubKey].createPublic().toString()) { loginFlag = true; if (privateKeys.isMasterKey) { @@ -370,7 +370,7 @@ export const getUpdatedUserKeys = async (currentAccountData, data) => { const privateKeys = getPrivateKeys(data.username, data.password); // Check all keys - Object.keys(publicKeys).map((pubKey) => { + Object.keys(publicKeys).forEach((pubKey) => { if (publicKeys[pubKey] === privateKeys[pubKey].createPublic().toString()) { loginFlag = true; } diff --git a/src/providers/queries/postQueries/postQueries.ts b/src/providers/queries/postQueries/postQueries.ts index 2afa4ac29..29a404343 100644 --- a/src/providers/queries/postQueries/postQueries.ts +++ b/src/providers/queries/postQueries/postQueries.ts @@ -112,7 +112,7 @@ export const useDiscussionQuery = (_author?: string, _permlink?: string) => { const [data, setData] = useState({}); const [sectionedData, setSectionedData] = useState([]); - const _fetchComments = async () => await getDiscussionCollection(author, permlink); + const _fetchComments = async () => getDiscussionCollection(author, permlink); const query = useQuery<{ [key: string]: Comment }>( [QUERIES.POST.GET_DISCUSSION, author, permlink], _fetchComments, diff --git a/src/redux/reducers/applicationReducer.ts b/src/redux/reducers/applicationReducer.ts index bf26a905f..ab334b805 100644 --- a/src/redux/reducers/applicationReducer.ts +++ b/src/redux/reducers/applicationReducer.ts @@ -14,8 +14,6 @@ import { IS_LOGIN_DONE, IS_NOTIFICATION_OPEN, LOGIN, - LOGOUT_DONE, - LOGOUT, SET_API, SET_CURRENCY, SET_LANGUAGE, diff --git a/src/screens/application/container/applicationContainer.tsx b/src/screens/application/container/applicationContainer.tsx index 5a759e754..d3fef1866 100644 --- a/src/screens/application/container/applicationContainer.tsx +++ b/src/screens/application/container/applicationContainer.tsx @@ -371,7 +371,6 @@ class ApplicationContainer extends Component { _getUserDataFromRealm = async () => { const { - intl, dispatch, isPinCodeOpen: _isPinCodeOpen, isConnected, @@ -647,7 +646,7 @@ class ApplicationContainer extends Component { bookmarkNotification: 15, }; - Object.keys(settings).map((item) => { + Object.keys(settings).forEach((item) => { if (notifyTypesConst[item] && settings[item]) { notify_types.push(notifyTypesConst[item]); } diff --git a/src/screens/backupKeysScreen/backupKeysScreen.tsx b/src/screens/backupKeysScreen/backupKeysScreen.tsx index 1dc633954..7b2d8035c 100644 --- a/src/screens/backupKeysScreen/backupKeysScreen.tsx +++ b/src/screens/backupKeysScreen/backupKeysScreen.tsx @@ -117,16 +117,6 @@ const BackupKeysScreen = () => { ); - const _renderNoKeys = () => ( - - - {intl.formatMessage({ - id: 'settings.backup_keys_modal.no_keys', - })} - - - ); - const _renderContent = ( {/* {currentAccount?.local?.authType === AUTH_TYPE.STEEM_CONNECT && _renderNoKeys()} */} diff --git a/src/screens/backupKeysScreen/importPrivateKeyModal.tsx b/src/screens/backupKeysScreen/importPrivateKeyModal.tsx index 5eadda90c..9ffea3b25 100644 --- a/src/screens/backupKeysScreen/importPrivateKeyModal.tsx +++ b/src/screens/backupKeysScreen/importPrivateKeyModal.tsx @@ -14,9 +14,7 @@ import { getUpdatedUserKeys } from '../../providers/hive/auth'; import { getDigitPinCode } from '../../providers/hive/dhive'; import { updateCurrentAccount } from '../../redux/actions/accountAction'; -type Props = {}; - -export const ImportPrivateKeyModalModal = forwardRef(({}: Props, ref) => { +export const ImportPrivateKeyModalModal = forwardRef(({}, ref) => { const intl = useIntl(); const dispatch = useDispatch(); diff --git a/src/screens/communities/container/communitiesContainer.js b/src/screens/communities/container/communitiesContainer.js index 51f377e3a..f2b3252f5 100644 --- a/src/screens/communities/container/communitiesContainer.js +++ b/src/screens/communities/container/communitiesContainer.js @@ -92,7 +92,7 @@ const CommunitiesContainer = ({ children }) => { useEffect(() => { const discoversData = [...discovers]; - Object.keys(subscribingCommunitiesInDiscoverTab).map((communityId) => { + Object.keys(subscribingCommunitiesInDiscoverTab).forEach((communityId) => { if (!subscribingCommunitiesInDiscoverTab[communityId].loading) { if (!subscribingCommunitiesInDiscoverTab[communityId].error) { if (subscribingCommunitiesInDiscoverTab[communityId].isSubscribed) { @@ -121,7 +121,7 @@ const CommunitiesContainer = ({ children }) => { subscribedCommunities.data, subscribedCommunitiesCache, ); - Object.keys(subscribingCommunitiesInJoinedTab).map((communityId) => { + Object.keys(subscribingCommunitiesInJoinedTab).forEach((communityId) => { if (!subscribingCommunitiesInJoinedTab[communityId].loading) { if (!subscribingCommunitiesInJoinedTab[communityId].error) { if (subscribingCommunitiesInJoinedTab[communityId].isSubscribed) { @@ -190,7 +190,7 @@ const CommunitiesContainer = ({ children }) => { }; const _invalidateSubscribedCommunityCache = (fetchedList) => { - fetchedList.map((listItem) => { + fetchedList.forEach((listItem) => { const itemExists = subscribedCommunitiesCache.get(listItem[0]); if (itemExists) { dispatch(deleteSubscribedCommunityCacheEntry(listItem[0])); diff --git a/src/screens/community/screen/communityScreen.js b/src/screens/community/screen/communityScreen.js index 9973f1c46..15d8b09f2 100644 --- a/src/screens/community/screen/communityScreen.js +++ b/src/screens/community/screen/communityScreen.js @@ -43,7 +43,7 @@ const CommunityScreen = ({ route }) => { } }; - _handleOnExpanded = () => { + const _handleOnExpanded = () => { if (!isExpanded) { setIsExpanded(true); } diff --git a/src/screens/editor/children/postOptionsModal.tsx b/src/screens/editor/children/postOptionsModal.tsx index cbf58aac6..95b2d572e 100644 --- a/src/screens/editor/children/postOptionsModal.tsx +++ b/src/screens/editor/children/postOptionsModal.tsx @@ -1,7 +1,7 @@ import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react'; import { useIntl } from 'react-intl'; import { View } from 'react-native'; -import Animated, { FlipInEasyX, FlipOutEasyX } from 'react-native-reanimated'; +import Animated, { FlipInEasyX } from 'react-native-reanimated'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import { BeneficiarySelectionContent, diff --git a/src/screens/editor/screen/editorScreen.tsx b/src/screens/editor/screen/editorScreen.tsx index 6d56c3011..7c15d0c15 100644 --- a/src/screens/editor/screen/editorScreen.tsx +++ b/src/screens/editor/screen/editorScreen.tsx @@ -9,7 +9,6 @@ import { extractMetadata, getWordsCount, makeJsonMetadata } from '../../../utils // Components import { BasicHeader, - PostForm, MarkdownEditor, SelectCommunityAreaView, SelectCommunityModalContainer, @@ -43,7 +42,6 @@ class EditorScreen extends Component { isFormValid: false, isPreviewActive: false, wordsCount: null, - isRemoveTag: false, fields: { title: (props.draftPost && props.draftPost.title) || '', body: (props.draftPost && props.draftPost.body) || '', @@ -142,7 +140,6 @@ class EditorScreen extends Component { tags: [], isValid: false, }, - isRemoveTag: true, }); if (initialEditor) { @@ -328,7 +325,7 @@ class EditorScreen extends Component { const { fields: _fields } = this.state; const __tags = tags; // .map((t) => t.replace(/([^a-z0-9-]+)/gi, '').toLowerCase()); const __fields = { ..._fields, tags: __tags }; - this.setState({ fields: __fields, isRemoveTag: false }, () => { + this.setState({ fields: __fields }, () => { this._handleFormUpdate('tag-area', __fields.tags); }); }; From ca95d5ea68729c72e471958d33a33fa7b75d3e34 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 18:34:39 +0500 Subject: [PATCH 044/111] lint errors less than 80 --- .../tabbedPosts/view/scrollTopPopup.tsx | 2 +- .../tabbedPosts/view/stackedTabBar.tsx | 1 - src/components/tooltip/tooltipView.tsx | 2 +- .../upvotePopover/container/upvotePopover.tsx | 8 +-- src/components/webViewModal/webViewModal.tsx | 4 +- src/containers/inAppPurchaseContainer.tsx | 13 +---- src/containers/transferContainer.js | 5 +- src/navigation/botomTabNavigator.tsx | 2 +- src/providers/ecency/converters.ts | 9 +--- src/providers/ecency/ecency.ts | 4 +- src/providers/ecency/ecency.types.ts | 2 +- src/providers/hive-engine/hiveEngine.ts | 4 +- src/providers/hive/dhive.js | 4 +- .../leaderboardQueries/leaderboardQueries.ts | 8 +-- .../queries/postQueries/postQueries.ts | 25 ++++----- .../queries/walletQueries/walletQueries.ts | 8 +-- src/redux/reducers/accountReducer.ts | 6 ++- src/redux/reducers/applicationReducer.ts | 6 ++- src/redux/reducers/cacheReducer.ts | 54 +++++++++---------- src/redux/reducers/communitiesReducer.js | 6 ++- src/redux/reducers/customTabsReducer.ts | 6 ++- src/redux/reducers/editorReducer.ts | 6 ++- src/redux/reducers/postsReducer.ts | 6 ++- src/redux/reducers/uiReducer.ts | 6 ++- src/redux/reducers/userReducer.js | 6 ++- src/redux/reducers/walkthroughReducer.ts | 6 ++- src/redux/reducers/walletReducer.ts | 6 ++- src/redux/store/store.ts | 2 +- .../assetDetails/children/coinChart.tsx | 2 +- .../children/delegationsModal.tsx | 1 + .../screen/assetDetailsScreen.tsx | 1 - .../assetsSelect/screen/assetsSelect.tsx | 6 +-- .../importPrivateKeyModal.tsx | 1 + .../editHistoryScreen/historyBuilder.tsx | 2 +- .../editor/container/editorContainer.tsx | 7 +-- src/screens/editor/screen/editorScreen.tsx | 14 ++--- 36 files changed, 120 insertions(+), 131 deletions(-) diff --git a/src/components/tabbedPosts/view/scrollTopPopup.tsx b/src/components/tabbedPosts/view/scrollTopPopup.tsx index 93aa46945..a5f36900a 100644 --- a/src/components/tabbedPosts/view/scrollTopPopup.tsx +++ b/src/components/tabbedPosts/view/scrollTopPopup.tsx @@ -40,7 +40,7 @@ const ScrollTopPopup = ({ {popupAvatars.map((url, index) => ( diff --git a/src/components/tabbedPosts/view/stackedTabBar.tsx b/src/components/tabbedPosts/view/stackedTabBar.tsx index 7181988c6..0e103e4c2 100644 --- a/src/components/tabbedPosts/view/stackedTabBar.tsx +++ b/src/components/tabbedPosts/view/stackedTabBar.tsx @@ -11,7 +11,6 @@ export interface TabItem { } interface StackedTabBarProps { - activeTab: boolean; goToPage: (pageIndex) => void; tabs: string[]; pageType?: 'main' | 'community' | 'profile' | 'ownProfile'; diff --git a/src/components/tooltip/tooltipView.tsx b/src/components/tooltip/tooltipView.tsx index a0c06f57a..14f71f7b9 100644 --- a/src/components/tooltip/tooltipView.tsx +++ b/src/components/tooltip/tooltipView.tsx @@ -38,7 +38,7 @@ const Tooltip = ({ children, text, walkthroughIndex }: TooltipProps, ref) => { }, })); - const _findAnchor = (e) => { + const _findAnchor = () => { if (touchableRef.current) { NativeModules.UIManager.measure(touchableRef.current, (x0, y0, width, height, x, y) => { setPopoverAnchor({ x, y, width, height }); diff --git a/src/components/upvotePopover/container/upvotePopover.tsx b/src/components/upvotePopover/container/upvotePopover.tsx index ddad5d37a..d6ecdd2dd 100644 --- a/src/components/upvotePopover/container/upvotePopover.tsx +++ b/src/components/upvotePopover/container/upvotePopover.tsx @@ -10,7 +10,7 @@ import get from 'lodash/get'; // Services and Actions import { Rect } from 'react-native-modal-popover/lib/PopoverGeometry'; -import { View, TouchableOpacity, Text, Alert } from 'react-native'; +import { View, TouchableOpacity, Text } from 'react-native'; import { Popover } from 'react-native-modal-popover'; import Slider from '@esteemapp/react-native-slider'; import { useIntl } from 'react-intl'; @@ -51,7 +51,6 @@ import { CacheStatus } from '../../../redux/reducers/cacheReducer'; import showLoginAlert from '../../../utils/showLoginAlert'; import { delay } from '../../../utils/editor'; -interface Props {} interface PopoverOptions { anchorRect: Rect; content: any; @@ -66,7 +65,8 @@ interface PopoverOptions { * */ -const UpvotePopover = forwardRef(({}: Props, ref) => { +// eslint-disable-next-line no-empty-pattern +const UpvotePopover = forwardRef(({}, ref) => { const intl = useIntl(); const dispatch = useAppDispatch(); @@ -234,7 +234,7 @@ const UpvotePopover = forwardRef(({}: Props, ref) => { // // when voting with same percent or other errors let errMsg = ''; if (err.message && err.message.indexOf(':') > 0) { - errMsg = err.message.split(': ')[1]; + [, errMsg] = err.message.split(': '); } else { errMsg = err.jse_shortmsg || err.error_description || err.message; } diff --git a/src/components/webViewModal/webViewModal.tsx b/src/components/webViewModal/webViewModal.tsx index 2b6dd7fa5..f36028e8d 100644 --- a/src/components/webViewModal/webViewModal.tsx +++ b/src/components/webViewModal/webViewModal.tsx @@ -5,14 +5,12 @@ import { useAppDispatch, useAppSelector } from '../../hooks'; import { hideWebViewModal } from '../../redux/actions/uiAction'; import { hsOptions } from '../../constants/hsOptions'; import { Modal } from '..'; -import styles from './webViewModalStyles'; -interface QRModalProps {} interface WebViewModalData { uri: string; } -export const WebViewModal = ({}: QRModalProps) => { +export const WebViewModal = () => { const dispatch = useAppDispatch(); const intl = useIntl(); const isVisibleWebViewModal = useAppSelector((state) => state.ui.isVisibleWebViewModal); diff --git a/src/containers/inAppPurchaseContainer.tsx b/src/containers/inAppPurchaseContainer.tsx index 8ec7255c9..5c59f210d 100644 --- a/src/containers/inAppPurchaseContainer.tsx +++ b/src/containers/inAppPurchaseContainer.tsx @@ -85,7 +85,6 @@ class InAppPurchaseContainer extends Component { _consumePurchase = async (purchase) => { const { currentAccount: { name }, - intl, fetchData, username, email, @@ -181,15 +180,7 @@ class InAppPurchaseContainer extends Component { this.purchaseUpdateSubscription = IAP.purchaseUpdatedListener(this._consumePurchase); this.purchaseErrorSubscription = IAP.purchaseErrorListener((error) => { - const { - currentAccount: { name }, - intl, - fetchData, - username, - email, - handleOnPurchaseFailure, - handleOnPurchaseSuccess, - } = this.props; + const { intl, handleOnPurchaseFailure } = this.props; bugsnagInstance.notify(error); if (get(error, 'responseCode') === '3' && Platform.OS === 'android') { @@ -336,7 +327,7 @@ class InAppPurchaseContainer extends Component { }, { text: intl.formatMessage({ id: 'alert.confirm' }), - onPress: async () => await this._buyItem(productId), + onPress: async () => this._buyItem(productId), }, ], headerContent: , diff --git a/src/containers/transferContainer.js b/src/containers/transferContainer.js index 898cd61a4..335a45479 100644 --- a/src/containers/transferContainer.js +++ b/src/containers/transferContainer.js @@ -119,7 +119,8 @@ class TransferContainer extends Component { balance = tokenBalance.stake; break; default: - balance = tokenBalance.balance; + const { balance: _balance } = tokenBalance; + balance = _balance; break; } } @@ -318,7 +319,7 @@ class TransferContainer extends Component { } if (!currentAccount.local) { const realmData = await getUserDataWithUsername(currentAccount.name); - currentAccount.local = realmData[0]; + [currentAccount.local] = realmData; } return func(currentAccount, pinCode, data) diff --git a/src/navigation/botomTabNavigator.tsx b/src/navigation/botomTabNavigator.tsx index bf49dfefa..46b28a624 100644 --- a/src/navigation/botomTabNavigator.tsx +++ b/src/navigation/botomTabNavigator.tsx @@ -3,7 +3,7 @@ import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import ROUTES from '../constants/routeNames'; import { BottomTabBar } from '../components'; -import { Feed, Notification, Profile, Wallet } from '../screens'; +import { Feed, Notification, Wallet } from '../screens'; import Waves from '../screens/waves'; const Tab = createBottomTabNavigator(); diff --git a/src/providers/ecency/converters.ts b/src/providers/ecency/converters.ts index d21f66a05..4536aaf57 100644 --- a/src/providers/ecency/converters.ts +++ b/src/providers/ecency/converters.ts @@ -1,13 +1,6 @@ import { ASSET_IDS } from '../../constants/defaultAssets'; import { Referral } from '../../models'; -import { - CommentHistoryItem, - LatestMarketPrices, - LatestQuotes, - QuoteItem, - ReferralStat, - Draft, -} from './ecency.types'; +import { CommentHistoryItem, LatestQuotes, QuoteItem, ReferralStat, Draft } from './ecency.types'; export const convertReferral = (rawData: any) => { return { diff --git a/src/providers/ecency/ecency.ts b/src/providers/ecency/ecency.ts index 7a53568ee..78ef30c7e 100644 --- a/src/providers/ecency/ecency.ts +++ b/src/providers/ecency/ecency.ts @@ -119,7 +119,7 @@ export const deleteDraft = async (draftId: string) => { /** * @param draft */ -export const addDraft = async (draft: Object) => { +export const addDraft = async (draft: any) => { const { title, body, tags, meta } = draft; try { const newDraft = { title, body, tags, meta }; @@ -151,7 +151,7 @@ export const updateDraft = async ( title: string, body: string, tags: string, - meta: Object, + meta: any, ) => { try { const data = { id: draftId, title, body, tags, meta }; diff --git a/src/providers/ecency/ecency.types.ts b/src/providers/ecency/ecency.types.ts index a534f6aef..fe4097ef1 100644 --- a/src/providers/ecency/ecency.types.ts +++ b/src/providers/ecency/ecency.types.ts @@ -52,7 +52,7 @@ export interface Draft { body: string; tags_arr: string[]; tags: string; - meta: Object; + meta: any; modified: string; created: string; timestamp: number; diff --git a/src/providers/hive-engine/hiveEngine.ts b/src/providers/hive-engine/hiveEngine.ts index efb198f2d..e9e6bf3cf 100644 --- a/src/providers/hive-engine/hiveEngine.ts +++ b/src/providers/hive-engine/hiveEngine.ts @@ -57,7 +57,7 @@ export const fetchTokenBalances = (account: string): Promise => return ecencyApi .post(PATH_ENGINE_CONTRACTS, data) .then((r) => r.data.result) - .catch((e) => { + .catch(() => { return []; }); }; @@ -79,7 +79,7 @@ export const fetchTokens = (tokens: string[]): Promise => { return ecencyApi .post(PATH_ENGINE_CONTRACTS, data) .then((r) => r.data.result) - .catch((e) => { + .catch(() => { return []; }); }; diff --git a/src/providers/hive/dhive.js b/src/providers/hive/dhive.js index 05fac84ac..450f4de1b 100644 --- a/src/providers/hive/dhive.js +++ b/src/providers/hive/dhive.js @@ -140,7 +140,9 @@ export const broadcastPostingJSON = async (id, json, currentAccount, pinHash) => accessToken: token, }); - return api.customJson([], [username], id, JSON.stringify(json)).then((r) => r.result); + return api + .customJson([], [currentAccount.username], id, JSON.stringify(json)) + .then((r) => r.result); } if (key) { diff --git a/src/providers/queries/leaderboardQueries/leaderboardQueries.ts b/src/providers/queries/leaderboardQueries/leaderboardQueries.ts index 5168c1f35..87aa872be 100644 --- a/src/providers/queries/leaderboardQueries/leaderboardQueries.ts +++ b/src/providers/queries/leaderboardQueries/leaderboardQueries.ts @@ -5,12 +5,8 @@ import QUERIES from '../queryKeys'; /** hook used to return user drafts */ export const useGetLeaderboardQuery = (duration: 'day' | 'week' | 'month') => { const _getLeaderboard = async () => { - try { - const data = await getLeaderboard(duration); - return data || []; - } catch (err) { - throw err; - } + const data = await getLeaderboard(duration); + return data || []; }; return useQuery([QUERIES.LEADERBOARD.GET, duration], _getLeaderboard); diff --git a/src/providers/queries/postQueries/postQueries.ts b/src/providers/queries/postQueries/postQueries.ts index 29a404343..862087375 100644 --- a/src/providers/queries/postQueries/postQueries.ts +++ b/src/providers/queries/postQueries/postQueries.ts @@ -168,24 +168,17 @@ export const useDiscussionQuery = (_author?: string, _permlink?: string) => { return replies; }; - for (const key in commentsMap) { - if (commentsMap.hasOwnProperty(key)) { - const comment = commentsMap[key]; + Object.keys(commentsMap).forEach((key) => { + const comment = commentsMap[key]; - // prcoess first level comment - if (comment && comment.parent_author === author && comment.parent_permlink === permlink) { - comment.commentKey = key; - comment.level = 1; - comment.repliesThread = parseReplies( - commentsMap, - comment.replies, - key, - comment.level + 1, - ); - comments.push(comment); - } + // prcoess first level comment + if (comment && comment.parent_author === author && comment.parent_permlink === permlink) { + comment.commentKey = key; + comment.level = 1; + comment.repliesThread = parseReplies(commentsMap, comment.replies, key, comment.level + 1); + comments.push(comment); } - } + }); setSectionedData(comments); }; diff --git a/src/providers/queries/walletQueries/walletQueries.ts b/src/providers/queries/walletQueries/walletQueries.ts index 07ba1c57a..49f7da19c 100644 --- a/src/providers/queries/walletQueries/walletQueries.ts +++ b/src/providers/queries/walletQueries/walletQueries.ts @@ -55,7 +55,7 @@ export const useUnclaimedRewardsQuery = () => { const _processCachedData = (rewardsCollection: RewardsCollection) => { if (claimsCollection) { const _curTime = new Date().getTime(); - for (const key in claimsCollection) { + Object.keys(claimsCollection).forEach((key) => { const _claimCache = claimsCollection[key]; const _rewardValue = rewardsCollection[key]; if ( @@ -67,7 +67,7 @@ export const useUnclaimedRewardsQuery = () => { ) { delete rewardsCollection[key]; } - } + }); } return rewardsCollection; @@ -239,11 +239,11 @@ export const useClaimRewardsMutation = () => { return isClaimingColl[assetId] || false; } - for (const key in isClaimingColl) { + Object.keys(isClaimingColl).forEach((key) => { if (isClaimingColl[key] === true) { return true; } - } + }); return false; }; diff --git a/src/redux/reducers/accountReducer.ts b/src/redux/reducers/accountReducer.ts index a6632db20..4d35a7221 100644 --- a/src/redux/reducers/accountReducer.ts +++ b/src/redux/reducers/accountReducer.ts @@ -42,7 +42,7 @@ const initialState: AccountState = { globalProps: null, }; -export default function (state = initialState, action) { +const accountReducer = (state = initialState, action) => { switch (action.type) { case FETCHING_ACCOUNT: return { @@ -134,4 +134,6 @@ export default function (state = initialState, action) { default: return state; } -} +}; + +export default accountReducer; diff --git a/src/redux/reducers/applicationReducer.ts b/src/redux/reducers/applicationReducer.ts index ab334b805..7515024ec 100644 --- a/src/redux/reducers/applicationReducer.ts +++ b/src/redux/reducers/applicationReducer.ts @@ -115,7 +115,7 @@ const initialState: State = { isBiometricEnabled: false, }; -export default function (state = initialState, action): State { +const applicationReducer = (state = initialState, action): State => { switch (action.type) { case LOGIN: return { @@ -302,4 +302,6 @@ export default function (state = initialState, action): State { default: return state; } -} +}; + +export default applicationReducer; diff --git a/src/redux/reducers/cacheReducer.ts b/src/redux/reducers/cacheReducer.ts index fcc42ed0e..e1f409fe4 100644 --- a/src/redux/reducers/cacheReducer.ts +++ b/src/redux/reducers/cacheReducer.ts @@ -111,7 +111,7 @@ const initialState: State = { lastUpdate: null, }; -export default function (state = initialState, action) { +const cacheReducer = (state = initialState, action) => { const { type, payload } = action; switch (type) { case UPDATE_VOTE_CACHE: @@ -252,47 +252,39 @@ export default function (state = initialState, action) { const currentTime = new Date().getTime(); if (state.votesCollection) { - for (const key in state.votesCollection) { - if (state.votesCollection.hasOwnProperty(key)) { - const vote = state.votesCollection[key]; - if (vote && (vote?.expiresAt || 0) < currentTime) { - delete state.votesCollection[key]; - } + Object.keys(state.votesCollection).forEach((key) => { + const vote = state.votesCollection[key]; + if (vote && (vote?.expiresAt || 0) < currentTime) { + delete state.votesCollection[key]; } - } + }); } if (state.commentsCollection) { - for (const key in state.commentsCollection) { - if (state.commentsCollection.hasOwnProperty(key)) { - const comment = state.commentsCollection[key]; - if (comment && (comment?.expiresAt || 0) < currentTime) { - delete state.commentsCollection[key]; - } + Object.keys(state.commentsCollection).forEach((key) => { + const comment = state.commentsCollection[key]; + if (comment && (comment?.expiresAt || 0) < currentTime) { + delete state.commentsCollection[key]; } - } + }); } if (state.draftsCollection) { - for (const key in state.draftsCollection) { - if (state.draftsCollection.hasOwnProperty(key)) { - const draft = state.draftsCollection[key]; - if (draft && ((draft?.expiresAt || 0) < currentTime || !draft.body)) { - delete state.draftsCollection[key]; - } + Object.keys(state.draftsCollection).forEach((key) => { + const draft = state.draftsCollection[key]; + if (draft && ((draft?.expiresAt || 0) < currentTime || !draft.body)) { + delete state.draftsCollection[key]; } - } + }); } if (state.claimsCollection) { - for (const key in state.claimsCollection) { - if (state.claimsCollection.hasOwnProperty(key)) { - const claim = state.claimsCollection[key]; - if (claim && (claim?.expiresAt || 0) < currentTime) { - delete state.claimsCollection[key]; - } + Object.keys(state.claimsCollection).forEach((key) => { + const claim = state.claimsCollection[key]; + if (claim && (claim?.expiresAt || 0) < currentTime) { + delete state.claimsCollection[key]; } - } + }); } if (state.subscribedCommunities && state.subscribedCommunities.size) { @@ -309,4 +301,6 @@ export default function (state = initialState, action) { default: return state; } -} +}; + +export default cacheReducer; diff --git a/src/redux/reducers/communitiesReducer.js b/src/redux/reducers/communitiesReducer.js index da73f696b..82444bbb7 100644 --- a/src/redux/reducers/communitiesReducer.js +++ b/src/redux/reducers/communitiesReducer.js @@ -56,7 +56,7 @@ const initialState = { }, }; -export default function (state = initialState, action) { +const communitiesReducer = (state = initialState, action) => { switch (action.type) { case FETCH_COMMUNITIES: return { @@ -460,4 +460,6 @@ export default function (state = initialState, action) { default: return state; } -} +}; + +export default communitiesReducer; diff --git a/src/redux/reducers/customTabsReducer.ts b/src/redux/reducers/customTabsReducer.ts index a9aec8ef3..d80f80202 100644 --- a/src/redux/reducers/customTabsReducer.ts +++ b/src/redux/reducers/customTabsReducer.ts @@ -25,7 +25,7 @@ const initialState: State = { ownProfileTabs: DEFAULT_OWN_PROFILE_FILTERS, }; -export default function (state: State = initialState, action): State { +const customTabsReducer = (state: State = initialState, action): State => { switch (action.type) { case SET_MAIN_TABS: return { @@ -54,4 +54,6 @@ export default function (state: State = initialState, action): State { default: return state; } -} +}; + +export default customTabsReducer; diff --git a/src/redux/reducers/editorReducer.ts b/src/redux/reducers/editorReducer.ts index 0a7e0edad..07be23fb4 100644 --- a/src/redux/reducers/editorReducer.ts +++ b/src/redux/reducers/editorReducer.ts @@ -17,7 +17,7 @@ const initialState: State = { beneficiariesMap: {}, }; -export default function (state = initialState, action) { +const editorReducer = (state = initialState, action) => { const { type, payload } = action; switch (type) { case SET_BENEFICIARIES: @@ -33,4 +33,6 @@ export default function (state = initialState, action) { default: return state; } -} +}; + +export default editorReducer; diff --git a/src/redux/reducers/postsReducer.ts b/src/redux/reducers/postsReducer.ts index 4640e8a6f..caff15390 100644 --- a/src/redux/reducers/postsReducer.ts +++ b/src/redux/reducers/postsReducer.ts @@ -20,7 +20,7 @@ const initialState = { feedScreenFilters: DEFAULT_FEED_FILTERS, }; -export default function (state = initialState, action) { +const postsReducer = (state = initialState, action) => { switch (action.type) { case SET_FEED_POSTS: return { @@ -75,4 +75,6 @@ export default function (state = initialState, action) { default: return state; } -} +}; + +export default postsReducer; diff --git a/src/redux/reducers/uiReducer.ts b/src/redux/reducers/uiReducer.ts index a20bc0341..757fc6264 100644 --- a/src/redux/reducers/uiReducer.ts +++ b/src/redux/reducers/uiReducer.ts @@ -63,7 +63,7 @@ const initialState: UiState = { isLogingOut: false, }; -export default function (state = initialState, action): UiState { +const uiReducer = (state = initialState, action): UiState => { switch (action.type) { case UPDATE_ACTIVE_BOTTOM_TAB: return { @@ -179,4 +179,6 @@ export default function (state = initialState, action): UiState { default: return state; } -} +}; + +export default uiReducer; diff --git a/src/redux/reducers/userReducer.js b/src/redux/reducers/userReducer.js index 8e0bd3893..728aac9c7 100644 --- a/src/redux/reducers/userReducer.js +++ b/src/redux/reducers/userReducer.js @@ -25,7 +25,7 @@ const initialState = { }, }; -export default function (state = initialState, action) { +const userReducer = (state = initialState, action) => { switch (action.type) { case FOLLOW_USER: return { @@ -129,4 +129,6 @@ export default function (state = initialState, action) { default: return state; } -} +}; + +export default userReducer; diff --git a/src/redux/reducers/walkthroughReducer.ts b/src/redux/reducers/walkthroughReducer.ts index 39389b5f4..b5671146b 100644 --- a/src/redux/reducers/walkthroughReducer.ts +++ b/src/redux/reducers/walkthroughReducer.ts @@ -11,7 +11,7 @@ interface State { const initialState: State = { walkthroughMap: new Map(), }; -export default function (state = initialState, action) { +const walkthroughReducer = (state = initialState, action) => { // console.log('action : ', action); const { type, payload } = action; @@ -28,4 +28,6 @@ export default function (state = initialState, action) { default: return state; } -} +}; + +export default walkthroughReducer; diff --git a/src/redux/reducers/walletReducer.ts b/src/redux/reducers/walletReducer.ts index 72789fe17..4f5b87986 100644 --- a/src/redux/reducers/walletReducer.ts +++ b/src/redux/reducers/walletReducer.ts @@ -95,7 +95,7 @@ const initialState: State = { updateTimestamp: 0, }; -export default function (state = initialState, action) { +const walletReducer = (state = initialState, action) => { const { type, payload } = action; switch (type) { case RESET_WALLET_DATA: { @@ -148,7 +148,9 @@ export default function (state = initialState, action) { default: return state; } -} +}; + +export default walletReducer; const ONE_HOUR_MS = 60 * 60 * 1000; const TEN_MIN_MS = 60 * 10 * 1000; diff --git a/src/redux/store/store.ts b/src/redux/store/store.ts index 387f6b64a..126445777 100644 --- a/src/redux/store/store.ts +++ b/src/redux/store/store.ts @@ -2,7 +2,7 @@ import { createStore, applyMiddleware, compose } from 'redux'; import thunk from 'redux-thunk'; import { createMigrate, createTransform, persistReducer, persistStore } from 'redux-persist'; -import AsyncStorage from '@react-native-community/async-storage'; +import AsyncStorage from '@react-native-async-storage/async-storage'; import Reactotron from '../../../reactotron-config'; import reducers from '../reducers'; diff --git a/src/screens/assetDetails/children/coinChart.tsx b/src/screens/assetDetails/children/coinChart.tsx index 1f9ce9b99..ce62def89 100644 --- a/src/screens/assetDetails/children/coinChart.tsx +++ b/src/screens/assetDetails/children/coinChart.tsx @@ -3,7 +3,7 @@ import { View } from 'react-native'; import { RangeSelector } from '.'; import { SimpleChart } from '../../../components'; import { useAppSelector } from '../../../hooks'; -import { ChartInterval, fetchMarketChart } from '../../../providers/coingecko/coingecko'; +import { fetchMarketChart } from '../../../providers/coingecko/coingecko'; import { fetchEngineMarketData } from '../../../providers/hive-engine/hiveEngine'; import getWindowDimensions from '../../../utils/getWindowDimensions'; import styles, { CHART_NEGATIVE_MARGIN } from './children.styles'; diff --git a/src/screens/assetDetails/children/delegationsModal.tsx b/src/screens/assetDetails/children/delegationsModal.tsx index af8a23a0a..412a58720 100644 --- a/src/screens/assetDetails/children/delegationsModal.tsx +++ b/src/screens/assetDetails/children/delegationsModal.tsx @@ -25,6 +25,7 @@ interface DelegationItem { timestamp: string; } +// eslint-disable-next-line no-empty-pattern export const DelegationsModal = forwardRef(({}, ref) => { const intl = useIntl(); const navigation = useNavigation>(); diff --git a/src/screens/assetDetails/screen/assetDetailsScreen.tsx b/src/screens/assetDetails/screen/assetDetailsScreen.tsx index 3dfb8271d..058c631eb 100644 --- a/src/screens/assetDetails/screen/assetDetailsScreen.tsx +++ b/src/screens/assetDetails/screen/assetDetailsScreen.tsx @@ -15,7 +15,6 @@ import { DelegationsModal, MODES } from '../children/delegationsModal'; import TransferTypes from '../../../constants/transferTypes'; import { walletQueries } from '../../../providers/queries'; import parseToken from '../../../utils/parseToken'; -import { log } from '../../../../reactotron-config'; export interface AssetDetailsScreenParams { coinId: string; diff --git a/src/screens/assetsSelect/screen/assetsSelect.tsx b/src/screens/assetsSelect/screen/assetsSelect.tsx index 07f0b091f..6488511bd 100644 --- a/src/screens/assetsSelect/screen/assetsSelect.tsx +++ b/src/screens/assetsSelect/screen/assetsSelect.tsx @@ -55,8 +55,8 @@ const AssetsSelect = ({ navigation }) => { useEffect(() => { const data: CoinData[] = []; - for (const key in coinsData) { - if (coinsData.hasOwnProperty(key) && (coinsData[key].isEngine || coinsData[key].isSpk)) { + Object.keys(coinsData).forEach((key) => { + if (coinsData[key].isEngine || coinsData[key].isSpk) { const asset: CoinData = coinsData[key]; const _name = asset.name.toLowerCase(); const _symbol = asset.symbol.toLowerCase(); @@ -69,7 +69,7 @@ const AssetsSelect = ({ navigation }) => { data.push(asset); } } - } + }); setListData(data); _updateSortedList({ data }); diff --git a/src/screens/backupKeysScreen/importPrivateKeyModal.tsx b/src/screens/backupKeysScreen/importPrivateKeyModal.tsx index 9ffea3b25..04bfd4cd1 100644 --- a/src/screens/backupKeysScreen/importPrivateKeyModal.tsx +++ b/src/screens/backupKeysScreen/importPrivateKeyModal.tsx @@ -14,6 +14,7 @@ import { getUpdatedUserKeys } from '../../providers/hive/auth'; import { getDigitPinCode } from '../../providers/hive/dhive'; import { updateCurrentAccount } from '../../redux/actions/accountAction'; +// eslint-disable-next-line no-empty-pattern export const ImportPrivateKeyModalModal = forwardRef(({}, ref) => { const intl = useIntl(); const dispatch = useDispatch(); diff --git a/src/screens/editHistoryScreen/historyBuilder.tsx b/src/screens/editHistoryScreen/historyBuilder.tsx index 0cad12a53..c0fb013e3 100644 --- a/src/screens/editHistoryScreen/historyBuilder.tsx +++ b/src/screens/editHistoryScreen/historyBuilder.tsx @@ -16,7 +16,7 @@ export default (raw: CommentHistoryItem[]) => { for (let l = 0; l < raw.length; l += 1) { if (raw[l].body.startsWith('@@')) { const p = dmp.patch_fromText(raw[l].body); - h = dmp.patch_apply(p, h)[0]; + [h] = dmp.patch_apply(p, h); raw[l].body = h; } else { h = raw[l].body; diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index ab0c98925..912499e95 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -107,10 +107,11 @@ class EditorContainer extends Component { if (route.params) { const navigationParams = route.params; - hasSharedIntent = navigationParams.hasSharedIntent; + const { hasSharedIntent: _hasShared, draftId: _draftId } = navigationParams; + hasSharedIntent = _hasShared; - if (navigationParams.draftId) { - draftId = navigationParams.draftId; + if (_draftId) { + draftId = _draftId; const cachedDrafts: any = queryClient.getQueryData([QUERIES.DRAFTS.GET]); if (cachedDrafts && cachedDrafts.length) { diff --git a/src/screens/editor/screen/editorScreen.tsx b/src/screens/editor/screen/editorScreen.tsx index 7c15d0c15..297470766 100644 --- a/src/screens/editor/screen/editorScreen.tsx +++ b/src/screens/editor/screen/editorScreen.tsx @@ -72,13 +72,6 @@ class EditorScreen extends Component { } } - componentWillUnmount() { - const { isEdit } = this.props; - if (!isEdit) { - this._saveDraftToDB(); - } - } - componentDidUpdate(prevProps, prevState) { const { isUploadingProp, communityProp } = this.state; if (prevState.isUploadingProp !== isUploadingProp) { @@ -91,6 +84,13 @@ class EditorScreen extends Component { } } + componentWillUnmount() { + const { isEdit } = this.props; + if (!isEdit) { + this._saveDraftToDB(); + } + } + static getDerivedStateFromProps(nextProps, prevState) { // shoudl update state const stateUpdate: any = {}; From bcfb97dd3f0eb49d87e7349f006527aba322e28f Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 2 Nov 2023 18:35:07 +0500 Subject: [PATCH 045/111] update react-codegen deployment target --- ios/Ecency.xcodeproj/project.pbxproj | 266 +++++++++++++-------------- 1 file changed, 131 insertions(+), 135 deletions(-) diff --git a/ios/Ecency.xcodeproj/project.pbxproj b/ios/Ecency.xcodeproj/project.pbxproj index c7ecb8cce..4235d0532 100644 --- a/ios/Ecency.xcodeproj/project.pbxproj +++ b/ios/Ecency.xcodeproj/project.pbxproj @@ -9,6 +9,7 @@ /* Begin PBXBuildFile section */ 00E356F31AD99517003FC87E /* EcencyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* EcencyTests.m */; }; 021526F0AF8A45FCB60C9C56 /* Roboto-medium.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 7900A87FFF214846B5FE0430 /* Roboto-medium.ttf */; }; + 04D1BA15BBCF7F2B9E3612BF /* libPods-Ecency-EcencyTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 0FDDF70C668E24276B7F7D91 /* libPods-Ecency-EcencyTests.a */; }; 0516470B24D2C513005DE9C5 /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0516470A24D2C513005DE9C5 /* ShareViewController.swift */; }; 0516470E24D2C513005DE9C5 /* MainInterface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 0516470C24D2C513005DE9C5 /* MainInterface.storyboard */; }; 0516471224D2C513005DE9C5 /* eshare.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 0516470824D2C513005DE9C5 /* eshare.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; @@ -28,16 +29,15 @@ 2D02E4BF1E0B4AB3006451C7 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; }; 2DCD954D1E0B4F2C00145EB5 /* EcencyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* EcencyTests.m */; }; 2E340255E74B48D8AF5B650C /* Sansation_Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 5ADE4B4B75DF437495E202D4 /* Sansation_Regular.ttf */; }; - 31159F09A2AEC018F2A3DBA4 /* libPods-Ecency-EcencyTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 2AEEE72F26D37DC0AC8A99C2 /* libPods-Ecency-EcencyTests.a */; }; + 31856ADD6C0311522CA1DFA7 /* libPods-Ecency.a in Frameworks */ = {isa = PBXBuildFile; fileRef = FA5F73032F66B1EBAA61B851 /* libPods-Ecency.a */; }; + 3ABD43432246ECAC42DCEE31 /* libPods-ImageNotifi.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 573C027160DB8491D45BFEA8 /* libPods-ImageNotifi.a */; }; 58F9BCC624793C61004F0790 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 58F9BCC224793C61004F0790 /* GoogleService-Info.plist */; }; 58F9BCC724793C61004F0790 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 58F9BCC224793C61004F0790 /* GoogleService-Info.plist */; }; 58F9BCC824793C61004F0790 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 58F9BCC224793C61004F0790 /* GoogleService-Info.plist */; }; 7C8D083700274C80BADEB3D6 /* Sansation_Bold.ttf in Resources */ = {isa = PBXBuildFile; fileRef = F1D77AE9F7B24CF19834052B /* Sansation_Bold.ttf */; }; - 872EB06D13C728B5C4C733E4 /* libPods-Ecency.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A897E6535C5B45DDED43406D /* libPods-Ecency.a */; }; 89D99F65314A416290F8D921 /* Roboto.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 64F2A611E6EF486C8D3FB82C /* Roboto.ttf */; }; 92082305364D41A4A673F950 /* RobotoMono-Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 5795D1B1C55E46FF96CC4AED /* RobotoMono-Regular.ttf */; }; A57EE8B63D4948F0A05218E3 /* rubicon-icon-font.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 65F56948860941D6BA55779F /* rubicon-icon-font.ttf */; }; - D59F45944E53C4F674EF4556 /* libPods-ImageNotifi.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A55BCE8805535F1786738BD /* libPods-ImageNotifi.a */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -117,26 +117,26 @@ 06844A5429119F05002FCC34 /* BootSplash.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = BootSplash.storyboard; path = Ecency/BootSplash.storyboard; sourceTree = ""; }; 06F72CA2290B2159003392F3 /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = Ecency/AppDelegate.mm; sourceTree = ""; }; 06F72CA5290B2D7F003392F3 /* hermes.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = hermes.xcframework; path = "Pods/hermes-engine/destroot/Library/Frameworks/universal/hermes.xcframework"; sourceTree = ""; }; + 0AA04D912D96044AECF20A65 /* Pods-Ecency.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency.debug.xcconfig"; path = "Target Support Files/Pods-Ecency/Pods-Ecency.debug.xcconfig"; sourceTree = ""; }; + 0FDDF70C668E24276B7F7D91 /* libPods-Ecency-EcencyTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Ecency-EcencyTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 112758B0BBF9458381CE41FD /* FontAwesome.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = FontAwesome.ttf; path = "../node_modules/react-native-vector-icons/Fonts/FontAwesome.ttf"; sourceTree = ""; }; 11CAB2F9B4B7425ABCAB4007 /* Foundation.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Foundation.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Foundation.ttf"; sourceTree = ""; }; 13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = Ecency/AppDelegate.h; sourceTree = ""; }; 13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = Ecency/Images.xcassets; sourceTree = ""; }; 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = Ecency/Info.plist; sourceTree = ""; }; 13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = Ecency/main.m; sourceTree = ""; }; - 17B14A55DE011F4183CA4FA1 /* Pods-Ecency-EcencyTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency-EcencyTests.release.xcconfig"; path = "Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests.release.xcconfig"; sourceTree = ""; }; 1CD0B89B258019B600A7D78E /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; + 1DFEA0938900B7C7E419498A /* Pods-Ecency-EcencyTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency-EcencyTests.release.xcconfig"; path = "Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests.release.xcconfig"; sourceTree = ""; }; 22F5F05A06E142C2B41A4D38 /* MaterialCommunityIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = MaterialCommunityIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf"; sourceTree = ""; }; - 25630E9BE79833145F3E34B9 /* Pods-Ecency.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency.release.xcconfig"; path = "Target Support Files/Pods-Ecency/Pods-Ecency.release.xcconfig"; sourceTree = ""; }; 263FA8C0EF21473FAAAD3EDD /* MaterialIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = MaterialIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/MaterialIcons.ttf"; sourceTree = ""; }; - 2AEEE72F26D37DC0AC8A99C2 /* libPods-Ecency-EcencyTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Ecency-EcencyTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 2D02E47B1E0B4A5D006451C7 /* Ecency-tvOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Ecency-tvOS.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 2D02E4901E0B4A5D006451C7 /* Ecency-tvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Ecency-tvOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; 34E88D888DD444F8B285363C /* SimpleLineIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = SimpleLineIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/SimpleLineIcons.ttf"; sourceTree = ""; }; + 404E707BFB0A754BDB18D41C /* Pods-Ecency-EcencyTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency-EcencyTests.debug.xcconfig"; path = "Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests.debug.xcconfig"; sourceTree = ""; }; 420ABF9795564845A0963C27 /* Feather.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Feather.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Feather.ttf"; sourceTree = ""; }; - 498D20DD8452BE4914FF168C /* Pods-ImageNotifi.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ImageNotifi.debug.xcconfig"; path = "Target Support Files/Pods-ImageNotifi/Pods-ImageNotifi.debug.xcconfig"; sourceTree = ""; }; + 4CA976A51F8781F23710B585 /* Pods-ImageNotifi.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ImageNotifi.release.xcconfig"; path = "Target Support Files/Pods-ImageNotifi/Pods-ImageNotifi.release.xcconfig"; sourceTree = ""; }; 4EB466C53BAE4EDC904357B3 /* FontAwesome5_Solid.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = FontAwesome5_Solid.ttf; path = "../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Solid.ttf"; sourceTree = ""; }; - 52B45846E7696881D299788C /* Pods-ImageNotifi.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ImageNotifi.release.xcconfig"; path = "Target Support Files/Pods-ImageNotifi/Pods-ImageNotifi.release.xcconfig"; sourceTree = ""; }; - 557F629CF9A41CBDA5C9B081 /* Pods-Ecency-ImageNotifi.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency-ImageNotifi.release.xcconfig"; path = "Target Support Files/Pods-Ecency-ImageNotifi/Pods-Ecency-ImageNotifi.release.xcconfig"; sourceTree = ""; }; + 573C027160DB8491D45BFEA8 /* libPods-ImageNotifi.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-ImageNotifi.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 5795D1B1C55E46FF96CC4AED /* RobotoMono-Regular.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = "RobotoMono-Regular.ttf"; path = "../src/assets/fonts/RobotoMono-Regular.ttf"; sourceTree = ""; }; 58190B3B23294814000EA0E1 /* StoreKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = StoreKit.framework; path = System/Library/Frameworks/StoreKit.framework; sourceTree = SDKROOT; }; 58190B3D23294823000EA0E1 /* Ecency.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; name = Ecency.entitlements; path = Ecency/Ecency.entitlements; sourceTree = ""; }; @@ -147,25 +147,23 @@ 58F6300F2350580B0017C953 /* libRealmJS.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; path = libRealmJS.a; sourceTree = BUILT_PRODUCTS_DIR; }; 58F9BCC224793C61004F0790 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; 5ADE4B4B75DF437495E202D4 /* Sansation_Regular.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Sansation_Regular.ttf; path = ../src/assets/fonts/Sansation_Regular.ttf; sourceTree = ""; }; - 637FA180975081FC81437804 /* Pods-Ecency-ImageNotifi.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency-ImageNotifi.debug.xcconfig"; path = "Target Support Files/Pods-Ecency-ImageNotifi/Pods-Ecency-ImageNotifi.debug.xcconfig"; sourceTree = ""; }; 64F2A611E6EF486C8D3FB82C /* Roboto.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Roboto.ttf; path = ../src/assets/fonts/Roboto.ttf; sourceTree = ""; }; 65F56948860941D6BA55779F /* rubicon-icon-font.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = "rubicon-icon-font.ttf"; path = "../src/assets/fonts/rubicon-icon-font.ttf"; sourceTree = ""; }; 6D935B44FB5A4CF3BF4D01DF /* Ionicons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Ionicons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Ionicons.ttf"; sourceTree = ""; }; - 7246575DADCA4488EC9D462A /* Pods-Ecency-EcencyTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency-EcencyTests.debug.xcconfig"; path = "Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests.debug.xcconfig"; sourceTree = ""; }; 7900A87FFF214846B5FE0430 /* Roboto-medium.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = "Roboto-medium.ttf"; path = "../src/assets/fonts/Roboto-medium.ttf"; sourceTree = ""; }; - 8A55BCE8805535F1786738BD /* libPods-ImageNotifi.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-ImageNotifi.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 83345398C95A01BA9C82A26A /* Pods-Ecency.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency.release.xcconfig"; path = "Target Support Files/Pods-Ecency/Pods-Ecency.release.xcconfig"; sourceTree = ""; }; 93B182C6FFA44610AB188D7C /* Entypo.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Entypo.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Entypo.ttf"; sourceTree = ""; }; 9464AFB033664B4F8E9F0BED /* AntDesign.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = AntDesign.ttf; path = "../node_modules/react-native-vector-icons/Fonts/AntDesign.ttf"; sourceTree = ""; }; 980BC9BC0D3B4AC69645C842 /* Zocial.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Zocial.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Zocial.ttf"; sourceTree = ""; }; 98D3D7C3AF354BF0987A2BFA /* Fontisto.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Fontisto.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Fontisto.ttf"; sourceTree = ""; }; 9BC08A790166415B9BB3F5CF /* FontAwesome5_Regular.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = FontAwesome5_Regular.ttf; path = "../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Regular.ttf"; sourceTree = ""; }; A239FC84622A4A9CA7950ED9 /* EvilIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = EvilIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/EvilIcons.ttf"; sourceTree = ""; }; - A897E6535C5B45DDED43406D /* libPods-Ecency.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Ecency.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - AEF4CD0A8BA6A1EC68545063 /* Pods-Ecency.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency.debug.xcconfig"; path = "Target Support Files/Pods-Ecency/Pods-Ecency.debug.xcconfig"; sourceTree = ""; }; BB1093ACCD904E2883413214 /* FontAwesome5_Brands.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = FontAwesome5_Brands.ttf; path = "../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Brands.ttf"; sourceTree = ""; }; + E71848FA34FB051BB9C34796 /* Pods-ImageNotifi.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ImageNotifi.debug.xcconfig"; path = "Target Support Files/Pods-ImageNotifi/Pods-ImageNotifi.debug.xcconfig"; sourceTree = ""; }; ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; }; ED2971642150620600B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS12.0.sdk/System/Library/Frameworks/JavaScriptCore.framework; sourceTree = DEVELOPER_DIR; }; F1D77AE9F7B24CF19834052B /* Sansation_Bold.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Sansation_Bold.ttf; path = ../src/assets/fonts/Sansation_Bold.ttf; sourceTree = ""; }; + FA5F73032F66B1EBAA61B851 /* libPods-Ecency.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Ecency.a"; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -173,7 +171,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 31159F09A2AEC018F2A3DBA4 /* libPods-Ecency-EcencyTests.a in Frameworks */, + 04D1BA15BBCF7F2B9E3612BF /* libPods-Ecency-EcencyTests.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -188,7 +186,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - D59F45944E53C4F674EF4556 /* libPods-ImageNotifi.a in Frameworks */, + 3ABD43432246ECAC42DCEE31 /* libPods-ImageNotifi.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -198,7 +196,7 @@ files = ( 05B6C49424C306CE00B7FA60 /* StoreKit.framework in Frameworks */, 065B9DDE2930E42A004310E4 /* hermes.xcframework in Frameworks */, - 872EB06D13C728B5C4C733E4 /* libPods-Ecency.a in Frameworks */, + 31856ADD6C0311522CA1DFA7 /* libPods-Ecency.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -282,14 +280,12 @@ 258E34A3BDFFFBF80D598187 /* Pods */ = { isa = PBXGroup; children = ( - AEF4CD0A8BA6A1EC68545063 /* Pods-Ecency.debug.xcconfig */, - 25630E9BE79833145F3E34B9 /* Pods-Ecency.release.xcconfig */, - 7246575DADCA4488EC9D462A /* Pods-Ecency-EcencyTests.debug.xcconfig */, - 17B14A55DE011F4183CA4FA1 /* Pods-Ecency-EcencyTests.release.xcconfig */, - 637FA180975081FC81437804 /* Pods-Ecency-ImageNotifi.debug.xcconfig */, - 557F629CF9A41CBDA5C9B081 /* Pods-Ecency-ImageNotifi.release.xcconfig */, - 498D20DD8452BE4914FF168C /* Pods-ImageNotifi.debug.xcconfig */, - 52B45846E7696881D299788C /* Pods-ImageNotifi.release.xcconfig */, + 0AA04D912D96044AECF20A65 /* Pods-Ecency.debug.xcconfig */, + 83345398C95A01BA9C82A26A /* Pods-Ecency.release.xcconfig */, + 404E707BFB0A754BDB18D41C /* Pods-Ecency-EcencyTests.debug.xcconfig */, + 1DFEA0938900B7C7E419498A /* Pods-Ecency-EcencyTests.release.xcconfig */, + E71848FA34FB051BB9C34796 /* Pods-ImageNotifi.debug.xcconfig */, + 4CA976A51F8781F23710B585 /* Pods-ImageNotifi.release.xcconfig */, ); path = Pods; sourceTree = ""; @@ -303,9 +299,9 @@ 58190B3B23294814000EA0E1 /* StoreKit.framework */, ED297162215061F000B7C4FE /* JavaScriptCore.framework */, ED2971642150620600B7C4FE /* JavaScriptCore.framework */, - A897E6535C5B45DDED43406D /* libPods-Ecency.a */, - 2AEEE72F26D37DC0AC8A99C2 /* libPods-Ecency-EcencyTests.a */, - 8A55BCE8805535F1786738BD /* libPods-ImageNotifi.a */, + FA5F73032F66B1EBAA61B851 /* libPods-Ecency.a */, + 0FDDF70C668E24276B7F7D91 /* libPods-Ecency-EcencyTests.a */, + 573C027160DB8491D45BFEA8 /* libPods-ImageNotifi.a */, ); name = Frameworks; sourceTree = ""; @@ -404,12 +400,12 @@ isa = PBXNativeTarget; buildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "EcencyTests" */; buildPhases = ( - 9A48C94417EBFC0599466A7A /* [CP] Check Pods Manifest.lock */, + C54D84D662D6C182DE045D38 /* [CP] Check Pods Manifest.lock */, 00E356EA1AD99517003FC87E /* Sources */, 00E356EB1AD99517003FC87E /* Frameworks */, 00E356EC1AD99517003FC87E /* Resources */, - 971975A45C595703A4946EE4 /* [CP] Embed Pods Frameworks */, - FBC6B780B4B7B61887A3D272 /* [CP] Copy Pods Resources */, + 5F1FB1470958FA150303E0F1 /* [CP] Embed Pods Frameworks */, + CAF063D667FC5B3B68512988 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -441,7 +437,7 @@ isa = PBXNativeTarget; buildConfigurationList = 057A51A92AD4962400E9A768 /* Build configuration list for PBXNativeTarget "ImageNotifi" */; buildPhases = ( - 1C81C8F285F08986579878AD /* [CP] Check Pods Manifest.lock */, + 1A5C8F8F41BED1BE8F97C47C /* [CP] Check Pods Manifest.lock */, 057A519C2AD4962300E9A768 /* Sources */, 057A519D2AD4962300E9A768 /* Frameworks */, 057A519E2AD4962300E9A768 /* Resources */, @@ -459,7 +455,7 @@ isa = PBXNativeTarget; buildConfigurationList = 05B6C4B424C306CE00B7FA60 /* Build configuration list for PBXNativeTarget "Ecency" */; buildPhases = ( - 7C134BDD9485660D3DDEF43A /* [CP] Check Pods Manifest.lock */, + A2B10E2CCC0492CF4778DDED /* [CP] Check Pods Manifest.lock */, 05B6C48E24C306CE00B7FA60 /* Start Packager */, 05B6C48F24C306CE00B7FA60 /* Sources */, 05B6C49324C306CE00B7FA60 /* Frameworks */, @@ -468,9 +464,9 @@ 58C9F50524CE017800A026DD /* Embed App Extensions */, 05BAAAEE25BF43F80072EA01 /* ShellScript */, 3D1F6693773C4541A695BB3C /* Upload source maps to Bugsnag */, - 2C87F1D159FEC7C0B7E3D88E /* [CP] Embed Pods Frameworks */, - 11982F6ABD16AEDAC94D6CFD /* [CP] Copy Pods Resources */, - F23609443C931B20A3F7BDA1 /* [CP-User] [RNFB] Core Configuration */, + C44924AC2FA92201E7EB2539 /* [CP] Embed Pods Frameworks */, + 7EEC7F0DE47D7C7CE8A3F289 /* [CP] Copy Pods Resources */, + DA796ED766580399CD1F9EFE /* [CP-User] [RNFB] Core Configuration */, ); buildRules = ( ); @@ -721,7 +717,81 @@ shellPath = /bin/sh; shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n"; }; - 11982F6ABD16AEDAC94D6CFD /* [CP] Copy Pods Resources */ = { + 1A5C8F8F41BED1BE8F97C47C /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-ImageNotifi-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 3D1F6693773C4541A695BB3C /* Upload source maps to Bugsnag */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Upload source maps to Bugsnag"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "SOURCE_MAP=\"$TMPDIR/$(md5 -qs \"$CONFIGURATION_BUILD_DIR\")-main.jsbundle.map\" ../node_modules/@bugsnag/react-native/bugsnag-react-native-xcode.sh"; + }; + 57F4EECD4004FE3420E6DF92 /* Bundle React Native Code And Images */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Bundle React Native Code And Images"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "export EXTRA_PACKAGER_ARGS=\"--sourcemap-output $TMPDIR/$(md5 -qs \"$CONFIGURATION_BUILD_DIR\")-main.jsbundle.map\"\nexport EXTRA_PACKAGER_ARGS=\"--sourcemap-output $CONFIGURATION_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/main.jsbundle.map\"\nexport NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh"; + }; + 5F1FB1470958FA150303E0F1 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests-frameworks.sh", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-DoubleConversion/double-conversion.framework/double-conversion", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-Glog/glog.framework/glog", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/OpenSSL-Universal/OpenSSL.framework/OpenSSL", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/hermes-engine/hermes.framework/hermes", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/double-conversion.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/glog.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/OpenSSL.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/hermes.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 7EEC7F0DE47D7C7CE8A3F289 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -775,7 +845,7 @@ shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency/Pods-Ecency-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 1C81C8F285F08986579878AD /* [CP] Check Pods Manifest.lock */ = { + A2B10E2CCC0492CF4778DDED /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -790,14 +860,14 @@ outputFileListPaths = ( ); outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-ImageNotifi-checkManifestLockResult.txt", + "$(DERIVED_FILE_DIR)/Pods-Ecency-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; - 2C87F1D159FEC7C0B7E3D88E /* [CP] Embed Pods Frameworks */ = { + C44924AC2FA92201E7EB2539 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -821,81 +891,7 @@ shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency/Pods-Ecency-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 3D1F6693773C4541A695BB3C /* Upload source maps to Bugsnag */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Upload source maps to Bugsnag"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "SOURCE_MAP=\"$TMPDIR/$(md5 -qs \"$CONFIGURATION_BUILD_DIR\")-main.jsbundle.map\" ../node_modules/@bugsnag/react-native/bugsnag-react-native-xcode.sh"; - }; - 57F4EECD4004FE3420E6DF92 /* Bundle React Native Code And Images */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Bundle React Native Code And Images"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "export EXTRA_PACKAGER_ARGS=\"--sourcemap-output $TMPDIR/$(md5 -qs \"$CONFIGURATION_BUILD_DIR\")-main.jsbundle.map\"\nexport EXTRA_PACKAGER_ARGS=\"--sourcemap-output $CONFIGURATION_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/main.jsbundle.map\"\nexport NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh"; - }; - 7C134BDD9485660D3DDEF43A /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Ecency-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 971975A45C595703A4946EE4 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests-frameworks.sh", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-DoubleConversion/double-conversion.framework/double-conversion", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-Glog/glog.framework/glog", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/OpenSSL-Universal/OpenSSL.framework/OpenSSL", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/hermes-engine/hermes.framework/hermes", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/double-conversion.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/glog.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/OpenSSL.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/hermes.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 9A48C94417EBFC0599466A7A /* [CP] Check Pods Manifest.lock */ = { + C54D84D662D6C182DE045D38 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -917,20 +913,7 @@ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; - F23609443C931B20A3F7BDA1 /* [CP-User] [RNFB] Core Configuration */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)", - ); - name = "[CP-User] [RNFB] Core Configuration"; - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "#!/usr/bin/env bash\n#\n# Copyright (c) 2016-present Invertase Limited & Contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this library except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nset -e\n\n_MAX_LOOKUPS=2;\n_SEARCH_RESULT=''\n_RN_ROOT_EXISTS=''\n_CURRENT_LOOKUPS=1\n_JSON_ROOT=\"'react-native'\"\n_JSON_FILE_NAME='firebase.json'\n_JSON_OUTPUT_BASE64='e30=' # { }\n_CURRENT_SEARCH_DIR=${PROJECT_DIR}\n_PLIST_BUDDY=/usr/libexec/PlistBuddy\n_TARGET_PLIST=\"${BUILT_PRODUCTS_DIR}/${INFOPLIST_PATH}\"\n_DSYM_PLIST=\"${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Info.plist\"\n\n# plist arrays\n_PLIST_ENTRY_KEYS=()\n_PLIST_ENTRY_TYPES=()\n_PLIST_ENTRY_VALUES=()\n\nfunction setPlistValue {\n echo \"info: setting plist entry '$1' of type '$2' in file '$4'\"\n ${_PLIST_BUDDY} -c \"Add :$1 $2 '$3'\" $4 || echo \"info: '$1' already exists\"\n}\n\nfunction getFirebaseJsonKeyValue () {\n if [[ ${_RN_ROOT_EXISTS} ]]; then\n ruby -e \"require 'rubygems';require 'json'; output=JSON.parse('$1'); puts output[$_JSON_ROOT]['$2']\"\n else\n echo \"\"\n fi;\n}\n\nfunction jsonBoolToYesNo () {\n if [[ $1 == \"false\" ]]; then\n echo \"NO\"\n elif [[ $1 == \"true\" ]]; then\n echo \"YES\"\n else echo \"NO\"\n fi\n}\n\necho \"info: -> RNFB build script started\"\necho \"info: 1) Locating ${_JSON_FILE_NAME} file:\"\n\nif [[ -z ${_CURRENT_SEARCH_DIR} ]]; then\n _CURRENT_SEARCH_DIR=$(pwd)\nfi;\n\nwhile true; do\n _CURRENT_SEARCH_DIR=$(dirname \"$_CURRENT_SEARCH_DIR\")\n if [[ \"$_CURRENT_SEARCH_DIR\" == \"/\" ]] || [[ ${_CURRENT_LOOKUPS} -gt ${_MAX_LOOKUPS} ]]; then break; fi;\n echo \"info: ($_CURRENT_LOOKUPS of $_MAX_LOOKUPS) Searching in '$_CURRENT_SEARCH_DIR' for a ${_JSON_FILE_NAME} file.\"\n _SEARCH_RESULT=$(find \"$_CURRENT_SEARCH_DIR\" -maxdepth 2 -name ${_JSON_FILE_NAME} -print | /usr/bin/head -n 1)\n if [[ ${_SEARCH_RESULT} ]]; then\n echo \"info: ${_JSON_FILE_NAME} found at $_SEARCH_RESULT\"\n break;\n fi;\n _CURRENT_LOOKUPS=$((_CURRENT_LOOKUPS+1))\ndone\n\nif [[ ${_SEARCH_RESULT} ]]; then\n _JSON_OUTPUT_RAW=$(cat \"${_SEARCH_RESULT}\")\n _RN_ROOT_EXISTS=$(ruby -e \"require 'rubygems';require 'json'; output=JSON.parse('$_JSON_OUTPUT_RAW'); puts output[$_JSON_ROOT]\" || echo '')\n\n if [[ ${_RN_ROOT_EXISTS} ]]; then\n if ! python3 --version >/dev/null 2>&1; then echo \"python3 not found, firebase.json file processing error.\" && exit 1; fi\n _JSON_OUTPUT_BASE64=$(python3 -c 'import json,sys,base64;print(base64.b64encode(bytes(json.dumps(json.loads(open('\"'${_SEARCH_RESULT}'\"', '\"'rb'\"').read())['${_JSON_ROOT}']), '\"'utf-8'\"')).decode())' || echo \"e30=\")\n fi\n\n _PLIST_ENTRY_KEYS+=(\"firebase_json_raw\")\n _PLIST_ENTRY_TYPES+=(\"string\")\n _PLIST_ENTRY_VALUES+=(\"$_JSON_OUTPUT_BASE64\")\n\n # config.app_data_collection_default_enabled\n _APP_DATA_COLLECTION_ENABLED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"app_data_collection_default_enabled\")\n if [[ $_APP_DATA_COLLECTION_ENABLED ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseDataCollectionDefaultEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_APP_DATA_COLLECTION_ENABLED\")\")\n fi\n\n # config.analytics_auto_collection_enabled\n _ANALYTICS_AUTO_COLLECTION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_auto_collection_enabled\")\n if [[ $_ANALYTICS_AUTO_COLLECTION ]]; then\n _PLIST_ENTRY_KEYS+=(\"FIREBASE_ANALYTICS_COLLECTION_ENABLED\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_AUTO_COLLECTION\")\")\n fi\n\n # config.analytics_collection_deactivated\n _ANALYTICS_DEACTIVATED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_collection_deactivated\")\n if [[ $_ANALYTICS_DEACTIVATED ]]; then\n _PLIST_ENTRY_KEYS+=(\"FIREBASE_ANALYTICS_COLLECTION_DEACTIVATED\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_DEACTIVATED\")\")\n fi\n\n # config.analytics_idfv_collection_enabled\n _ANALYTICS_IDFV_COLLECTION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_idfv_collection_enabled\")\n if [[ $_ANALYTICS_IDFV_COLLECTION ]]; then\n _PLIST_ENTRY_KEYS+=(\"GOOGLE_ANALYTICS_IDFV_COLLECTION_ENABLED\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_IDFV_COLLECTION\")\")\n fi\n\n # config.analytics_default_allow_ad_personalization_signals\n _ANALYTICS_PERSONALIZATION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_default_allow_ad_personalization_signals\")\n if [[ $_ANALYTICS_PERSONALIZATION ]]; then\n _PLIST_ENTRY_KEYS+=(\"GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_PERSONALIZATION\")\")\n fi\n\n # config.google_analytics_automatic_screen_reporting_enabled\n _ANALYTICS_AUTO_SCREEN_REPORTING=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"google_analytics_automatic_screen_reporting_enabled\")\n if [[ $_ANALYTICS_AUTO_SCREEN_REPORTING ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseAutomaticScreenReportingEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_AUTO_SCREEN_REPORTING\")\")\n fi\n\n # config.perf_auto_collection_enabled\n _PERF_AUTO_COLLECTION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"perf_auto_collection_enabled\")\n if [[ $_PERF_AUTO_COLLECTION ]]; then\n _PLIST_ENTRY_KEYS+=(\"firebase_performance_collection_enabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_PERF_AUTO_COLLECTION\")\")\n fi\n\n # config.perf_collection_deactivated\n _PERF_DEACTIVATED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"perf_collection_deactivated\")\n if [[ $_PERF_DEACTIVATED ]]; then\n _PLIST_ENTRY_KEYS+=(\"firebase_performance_collection_deactivated\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_PERF_DEACTIVATED\")\")\n fi\n\n # config.messaging_auto_init_enabled\n _MESSAGING_AUTO_INIT=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"messaging_auto_init_enabled\")\n if [[ $_MESSAGING_AUTO_INIT ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseMessagingAutoInitEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_MESSAGING_AUTO_INIT\")\")\n fi\n\n # config.in_app_messaging_auto_colllection_enabled\n _FIAM_AUTO_INIT=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"in_app_messaging_auto_collection_enabled\")\n if [[ $_FIAM_AUTO_INIT ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseInAppMessagingAutomaticDataCollectionEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_FIAM_AUTO_INIT\")\")\n fi\n\n # config.app_check_token_auto_refresh\n _APP_CHECK_TOKEN_AUTO_REFRESH=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"app_check_token_auto_refresh\")\n if [[ $_APP_CHECK_TOKEN_AUTO_REFRESH ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseAppCheckTokenAutoRefreshEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_APP_CHECK_TOKEN_AUTO_REFRESH\")\")\n fi\n\n # config.crashlytics_disable_auto_disabler - undocumented for now - mainly for debugging, document if becomes useful\n _CRASHLYTICS_AUTO_DISABLE_ENABLED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"crashlytics_disable_auto_disabler\")\n if [[ $_CRASHLYTICS_AUTO_DISABLE_ENABLED == \"true\" ]]; then\n echo \"Disabled Crashlytics auto disabler.\" # do nothing\n else\n _PLIST_ENTRY_KEYS+=(\"FirebaseCrashlyticsCollectionEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"NO\")\n fi\nelse\n _PLIST_ENTRY_KEYS+=(\"firebase_json_raw\")\n _PLIST_ENTRY_TYPES+=(\"string\")\n _PLIST_ENTRY_VALUES+=(\"$_JSON_OUTPUT_BASE64\")\n echo \"warning: A firebase.json file was not found, whilst this file is optional it is recommended to include it to configure firebase services in React Native Firebase.\"\nfi;\n\necho \"info: 2) Injecting Info.plist entries: \"\n\n# Log out the keys we're adding\nfor i in \"${!_PLIST_ENTRY_KEYS[@]}\"; do\n echo \" -> $i) ${_PLIST_ENTRY_KEYS[$i]}\" \"${_PLIST_ENTRY_TYPES[$i]}\" \"${_PLIST_ENTRY_VALUES[$i]}\"\ndone\n\nfor plist in \"${_TARGET_PLIST}\" \"${_DSYM_PLIST}\" ; do\n if [[ -f \"${plist}\" ]]; then\n\n # paths with spaces break the call to setPlistValue. temporarily modify\n # the shell internal field separator variable (IFS), which normally\n # includes spaces, to consist only of line breaks\n oldifs=$IFS\n IFS=\"\n\"\n\n for i in \"${!_PLIST_ENTRY_KEYS[@]}\"; do\n setPlistValue \"${_PLIST_ENTRY_KEYS[$i]}\" \"${_PLIST_ENTRY_TYPES[$i]}\" \"${_PLIST_ENTRY_VALUES[$i]}\" \"${plist}\"\n done\n\n # restore the original internal field separator value\n IFS=$oldifs\n else\n echo \"warning: A Info.plist build output file was not found (${plist})\"\n fi\ndone\n\necho \"info: <- RNFB build script finished\"\n"; - }; - FBC6B780B4B7B61887A3D272 /* [CP] Copy Pods Resources */ = { + CAF063D667FC5B3B68512988 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -984,6 +967,19 @@ shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests-resources.sh\"\n"; showEnvVarsInLog = 0; }; + DA796ED766580399CD1F9EFE /* [CP-User] [RNFB] Core Configuration */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)", + ); + name = "[CP-User] [RNFB] Core Configuration"; + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "#!/usr/bin/env bash\n#\n# Copyright (c) 2016-present Invertase Limited & Contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this library except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nset -e\n\n_MAX_LOOKUPS=2;\n_SEARCH_RESULT=''\n_RN_ROOT_EXISTS=''\n_CURRENT_LOOKUPS=1\n_JSON_ROOT=\"'react-native'\"\n_JSON_FILE_NAME='firebase.json'\n_JSON_OUTPUT_BASE64='e30=' # { }\n_CURRENT_SEARCH_DIR=${PROJECT_DIR}\n_PLIST_BUDDY=/usr/libexec/PlistBuddy\n_TARGET_PLIST=\"${BUILT_PRODUCTS_DIR}/${INFOPLIST_PATH}\"\n_DSYM_PLIST=\"${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Info.plist\"\n\n# plist arrays\n_PLIST_ENTRY_KEYS=()\n_PLIST_ENTRY_TYPES=()\n_PLIST_ENTRY_VALUES=()\n\nfunction setPlistValue {\n echo \"info: setting plist entry '$1' of type '$2' in file '$4'\"\n ${_PLIST_BUDDY} -c \"Add :$1 $2 '$3'\" $4 || echo \"info: '$1' already exists\"\n}\n\nfunction getFirebaseJsonKeyValue () {\n if [[ ${_RN_ROOT_EXISTS} ]]; then\n ruby -e \"require 'rubygems';require 'json'; output=JSON.parse('$1'); puts output[$_JSON_ROOT]['$2']\"\n else\n echo \"\"\n fi;\n}\n\nfunction jsonBoolToYesNo () {\n if [[ $1 == \"false\" ]]; then\n echo \"NO\"\n elif [[ $1 == \"true\" ]]; then\n echo \"YES\"\n else echo \"NO\"\n fi\n}\n\necho \"info: -> RNFB build script started\"\necho \"info: 1) Locating ${_JSON_FILE_NAME} file:\"\n\nif [[ -z ${_CURRENT_SEARCH_DIR} ]]; then\n _CURRENT_SEARCH_DIR=$(pwd)\nfi;\n\nwhile true; do\n _CURRENT_SEARCH_DIR=$(dirname \"$_CURRENT_SEARCH_DIR\")\n if [[ \"$_CURRENT_SEARCH_DIR\" == \"/\" ]] || [[ ${_CURRENT_LOOKUPS} -gt ${_MAX_LOOKUPS} ]]; then break; fi;\n echo \"info: ($_CURRENT_LOOKUPS of $_MAX_LOOKUPS) Searching in '$_CURRENT_SEARCH_DIR' for a ${_JSON_FILE_NAME} file.\"\n _SEARCH_RESULT=$(find \"$_CURRENT_SEARCH_DIR\" -maxdepth 2 -name ${_JSON_FILE_NAME} -print | /usr/bin/head -n 1)\n if [[ ${_SEARCH_RESULT} ]]; then\n echo \"info: ${_JSON_FILE_NAME} found at $_SEARCH_RESULT\"\n break;\n fi;\n _CURRENT_LOOKUPS=$((_CURRENT_LOOKUPS+1))\ndone\n\nif [[ ${_SEARCH_RESULT} ]]; then\n _JSON_OUTPUT_RAW=$(cat \"${_SEARCH_RESULT}\")\n _RN_ROOT_EXISTS=$(ruby -e \"require 'rubygems';require 'json'; output=JSON.parse('$_JSON_OUTPUT_RAW'); puts output[$_JSON_ROOT]\" || echo '')\n\n if [[ ${_RN_ROOT_EXISTS} ]]; then\n if ! python3 --version >/dev/null 2>&1; then echo \"python3 not found, firebase.json file processing error.\" && exit 1; fi\n _JSON_OUTPUT_BASE64=$(python3 -c 'import json,sys,base64;print(base64.b64encode(bytes(json.dumps(json.loads(open('\"'${_SEARCH_RESULT}'\"', '\"'rb'\"').read())['${_JSON_ROOT}']), '\"'utf-8'\"')).decode())' || echo \"e30=\")\n fi\n\n _PLIST_ENTRY_KEYS+=(\"firebase_json_raw\")\n _PLIST_ENTRY_TYPES+=(\"string\")\n _PLIST_ENTRY_VALUES+=(\"$_JSON_OUTPUT_BASE64\")\n\n # config.app_data_collection_default_enabled\n _APP_DATA_COLLECTION_ENABLED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"app_data_collection_default_enabled\")\n if [[ $_APP_DATA_COLLECTION_ENABLED ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseDataCollectionDefaultEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_APP_DATA_COLLECTION_ENABLED\")\")\n fi\n\n # config.analytics_auto_collection_enabled\n _ANALYTICS_AUTO_COLLECTION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_auto_collection_enabled\")\n if [[ $_ANALYTICS_AUTO_COLLECTION ]]; then\n _PLIST_ENTRY_KEYS+=(\"FIREBASE_ANALYTICS_COLLECTION_ENABLED\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_AUTO_COLLECTION\")\")\n fi\n\n # config.analytics_collection_deactivated\n _ANALYTICS_DEACTIVATED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_collection_deactivated\")\n if [[ $_ANALYTICS_DEACTIVATED ]]; then\n _PLIST_ENTRY_KEYS+=(\"FIREBASE_ANALYTICS_COLLECTION_DEACTIVATED\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_DEACTIVATED\")\")\n fi\n\n # config.analytics_idfv_collection_enabled\n _ANALYTICS_IDFV_COLLECTION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_idfv_collection_enabled\")\n if [[ $_ANALYTICS_IDFV_COLLECTION ]]; then\n _PLIST_ENTRY_KEYS+=(\"GOOGLE_ANALYTICS_IDFV_COLLECTION_ENABLED\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_IDFV_COLLECTION\")\")\n fi\n\n # config.analytics_default_allow_ad_personalization_signals\n _ANALYTICS_PERSONALIZATION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_default_allow_ad_personalization_signals\")\n if [[ $_ANALYTICS_PERSONALIZATION ]]; then\n _PLIST_ENTRY_KEYS+=(\"GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_PERSONALIZATION\")\")\n fi\n\n # config.google_analytics_automatic_screen_reporting_enabled\n _ANALYTICS_AUTO_SCREEN_REPORTING=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"google_analytics_automatic_screen_reporting_enabled\")\n if [[ $_ANALYTICS_AUTO_SCREEN_REPORTING ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseAutomaticScreenReportingEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_AUTO_SCREEN_REPORTING\")\")\n fi\n\n # config.perf_auto_collection_enabled\n _PERF_AUTO_COLLECTION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"perf_auto_collection_enabled\")\n if [[ $_PERF_AUTO_COLLECTION ]]; then\n _PLIST_ENTRY_KEYS+=(\"firebase_performance_collection_enabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_PERF_AUTO_COLLECTION\")\")\n fi\n\n # config.perf_collection_deactivated\n _PERF_DEACTIVATED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"perf_collection_deactivated\")\n if [[ $_PERF_DEACTIVATED ]]; then\n _PLIST_ENTRY_KEYS+=(\"firebase_performance_collection_deactivated\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_PERF_DEACTIVATED\")\")\n fi\n\n # config.messaging_auto_init_enabled\n _MESSAGING_AUTO_INIT=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"messaging_auto_init_enabled\")\n if [[ $_MESSAGING_AUTO_INIT ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseMessagingAutoInitEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_MESSAGING_AUTO_INIT\")\")\n fi\n\n # config.in_app_messaging_auto_colllection_enabled\n _FIAM_AUTO_INIT=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"in_app_messaging_auto_collection_enabled\")\n if [[ $_FIAM_AUTO_INIT ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseInAppMessagingAutomaticDataCollectionEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_FIAM_AUTO_INIT\")\")\n fi\n\n # config.app_check_token_auto_refresh\n _APP_CHECK_TOKEN_AUTO_REFRESH=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"app_check_token_auto_refresh\")\n if [[ $_APP_CHECK_TOKEN_AUTO_REFRESH ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseAppCheckTokenAutoRefreshEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_APP_CHECK_TOKEN_AUTO_REFRESH\")\")\n fi\n\n # config.crashlytics_disable_auto_disabler - undocumented for now - mainly for debugging, document if becomes useful\n _CRASHLYTICS_AUTO_DISABLE_ENABLED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"crashlytics_disable_auto_disabler\")\n if [[ $_CRASHLYTICS_AUTO_DISABLE_ENABLED == \"true\" ]]; then\n echo \"Disabled Crashlytics auto disabler.\" # do nothing\n else\n _PLIST_ENTRY_KEYS+=(\"FirebaseCrashlyticsCollectionEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"NO\")\n fi\nelse\n _PLIST_ENTRY_KEYS+=(\"firebase_json_raw\")\n _PLIST_ENTRY_TYPES+=(\"string\")\n _PLIST_ENTRY_VALUES+=(\"$_JSON_OUTPUT_BASE64\")\n echo \"warning: A firebase.json file was not found, whilst this file is optional it is recommended to include it to configure firebase services in React Native Firebase.\"\nfi;\n\necho \"info: 2) Injecting Info.plist entries: \"\n\n# Log out the keys we're adding\nfor i in \"${!_PLIST_ENTRY_KEYS[@]}\"; do\n echo \" -> $i) ${_PLIST_ENTRY_KEYS[$i]}\" \"${_PLIST_ENTRY_TYPES[$i]}\" \"${_PLIST_ENTRY_VALUES[$i]}\"\ndone\n\nfor plist in \"${_TARGET_PLIST}\" \"${_DSYM_PLIST}\" ; do\n if [[ -f \"${plist}\" ]]; then\n\n # paths with spaces break the call to setPlistValue. temporarily modify\n # the shell internal field separator variable (IFS), which normally\n # includes spaces, to consist only of line breaks\n oldifs=$IFS\n IFS=\"\n\"\n\n for i in \"${!_PLIST_ENTRY_KEYS[@]}\"; do\n setPlistValue \"${_PLIST_ENTRY_KEYS[$i]}\" \"${_PLIST_ENTRY_TYPES[$i]}\" \"${_PLIST_ENTRY_VALUES[$i]}\" \"${plist}\"\n done\n\n # restore the original internal field separator value\n IFS=$oldifs\n else\n echo \"warning: A Info.plist build output file was not found (${plist})\"\n fi\ndone\n\necho \"info: <- RNFB build script finished\"\n"; + }; FD10A7F122414F3F0027D42C /* Start Packager */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -1091,7 +1087,7 @@ /* Begin XCBuildConfiguration section */ 00E356F61AD99517003FC87E /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 7246575DADCA4488EC9D462A /* Pods-Ecency-EcencyTests.debug.xcconfig */; + baseConfigurationReference = 404E707BFB0A754BDB18D41C /* Pods-Ecency-EcencyTests.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; @@ -1128,7 +1124,7 @@ }; 00E356F71AD99517003FC87E /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 17B14A55DE011F4183CA4FA1 /* Pods-Ecency-EcencyTests.release.xcconfig */; + baseConfigurationReference = 1DFEA0938900B7C7E419498A /* Pods-Ecency-EcencyTests.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; @@ -1240,7 +1236,7 @@ }; 057A51AA2AD4962400E9A768 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 498D20DD8452BE4914FF168C /* Pods-ImageNotifi.debug.xcconfig */; + baseConfigurationReference = E71848FA34FB051BB9C34796 /* Pods-ImageNotifi.debug.xcconfig */; buildSettings = { CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; @@ -1283,7 +1279,7 @@ }; 057A51AB2AD4962400E9A768 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 52B45846E7696881D299788C /* Pods-ImageNotifi.release.xcconfig */; + baseConfigurationReference = 4CA976A51F8781F23710B585 /* Pods-ImageNotifi.release.xcconfig */; buildSettings = { CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; @@ -1326,7 +1322,7 @@ }; 05B6C4B524C306CE00B7FA60 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = AEF4CD0A8BA6A1EC68545063 /* Pods-Ecency.debug.xcconfig */; + baseConfigurationReference = 0AA04D912D96044AECF20A65 /* Pods-Ecency.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; @@ -1411,7 +1407,7 @@ }; 05B6C4B624C306CE00B7FA60 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 25630E9BE79833145F3E34B9 /* Pods-Ecency.release.xcconfig */; + baseConfigurationReference = 83345398C95A01BA9C82A26A /* Pods-Ecency.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; From aab3c40f32f7d43bd7a59293280d59707655777b Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 3 Nov 2023 14:50:47 +0500 Subject: [PATCH 046/111] lint errors down to 20 --- .../view/selectCommunityAreaView.js | 3 +- .../view/selectCommunityModalView.tsx | 1 - .../filterBar/view/filterBarView.tsx | 2 +- src/components/header/view/headerStyles.ts | 2 +- .../insertLinkModal/insertLinkModal.tsx | 5 +- .../view/markdownEditorView.tsx | 16 +- .../notification/view/notificationView.tsx | 5 +- .../container/inputSupportModal.tsx | 2 +- .../children/profileBasic.tsx | 1 - .../children/quickProfileContent.tsx | 2 +- .../views/pinAnimatedInputView.js | 6 +- .../postCard/children/upvoteButton.tsx | 11 +- .../postComments/children/commentsSection.tsx | 2 +- .../postElements/body/view/postBodyView.js | 3 +- .../postHtmlRenderer/linkDataParser.ts | 3 +- .../postHtmlRenderer/postHtmlRenderer.tsx | 4 +- .../container/postDisplayContainer.tsx | 2 +- .../postView/view/postDisplayView.tsx | 7 +- .../container/postsListContainer.tsx | 2 +- .../profile/children/commentsTabContent.tsx | 4 +- src/components/profile/profileView.js | 4 - src/components/qrModal/qrModalView.tsx | 3 +- .../quickReplyModalContent.tsx | 1 - .../snippetEditorModal/snippetEditorModal.tsx | 2 +- .../view/subscribedCommunitiesListView.js | 3 +- .../tabbedPosts/services/tabbedPostsModels.ts | 2 - .../tabbedPosts/view/listEmptyView.tsx | 13 +- .../container/uploadsGalleryModal.tsx | 8 +- src/containers/inAppPurchaseContainer.tsx | 1 + src/providers/hive/dhive.js | 140 +++++++++--------- src/providers/queries/draftQueries.ts | 5 +- src/providers/queries/editorQueries.ts | 2 + .../assetDetails/children/activitiesList.tsx | 4 +- .../screen/assetDetailsScreen.tsx | 2 +- 34 files changed, 127 insertions(+), 146 deletions(-) diff --git a/src/components/editorElements/selectCommunityArea/view/selectCommunityAreaView.js b/src/components/editorElements/selectCommunityArea/view/selectCommunityAreaView.js index 7ccd24325..02da8002a 100644 --- a/src/components/editorElements/selectCommunityArea/view/selectCommunityAreaView.js +++ b/src/components/editorElements/selectCommunityArea/view/selectCommunityAreaView.js @@ -20,7 +20,8 @@ const SelectCommunityAreaView = ({ if (selectedCommunity) { username = selectedCommunity.name; - title = selectedCommunity.title; + const { title: _title } = selectedCommunity; + title = _title; } else if (selectedAccount) { username = selectedAccount.name; title = intl.formatMessage({ id: 'editor.my_blog' }); diff --git a/src/components/editorElements/selectCommunityModal/view/selectCommunityModalView.tsx b/src/components/editorElements/selectCommunityModal/view/selectCommunityModalView.tsx index bc6a89a71..d4654cc3f 100644 --- a/src/components/editorElements/selectCommunityModal/view/selectCommunityModalView.tsx +++ b/src/components/editorElements/selectCommunityModal/view/selectCommunityModalView.tsx @@ -14,7 +14,6 @@ const SelectCommunityModalView = ({ subscribedCommunities, onPressCommunity, onChangeSearch, - onPressCloseForSearch, searchedCommunities, showSearchedCommunities, currentAccount, diff --git a/src/components/filterBar/view/filterBarView.tsx b/src/components/filterBar/view/filterBarView.tsx index 5d2d27aec..ec816a205 100644 --- a/src/components/filterBar/view/filterBarView.tsx +++ b/src/components/filterBar/view/filterBarView.tsx @@ -76,7 +76,7 @@ const FilterBarView = ({ {options.map((item, index) => ( ({ showModal: async ({ selectedText, selection }) => { if (selectedText) { - setSelectedText(selectedText); setSelection(selection); if (selection && selection.start !== selection.end) { if (isStringWebLink(selectedText)) { @@ -97,7 +95,7 @@ export const InsertLinkModal = forwardRef( } }; - const _setFormattedTextAndSelection = ({ selection, text }) => { + const _setFormattedTextAndSelection = ({ text }) => { setPreviewBody(renderPostBody(text, true, Platform.OS !== 'ios')); setFormattedText(text); }; @@ -117,7 +115,6 @@ export const InsertLinkModal = forwardRef( setSelectedUrlType(0); setPreviewBody(''); setIsUrlValid(true); - setSelectedText(''); setFormattedText(''); handleOnSheetClose(); }; diff --git a/src/components/markdownEditor/view/markdownEditorView.tsx b/src/components/markdownEditor/view/markdownEditorView.tsx index bdb39142a..a78fc774c 100644 --- a/src/components/markdownEditor/view/markdownEditorView.tsx +++ b/src/components/markdownEditor/view/markdownEditorView.tsx @@ -179,14 +179,14 @@ const MarkdownEditorView = ({ dispatch(toggleAccountsBottomSheet(!isVisibleAccountsBottomSheet)); }; - const _onApplyUsername = (username) => { - applyUsername({ - text: bodyTextRef.current, - selection: bodySelectionRef.current, - setTextAndSelection: _setTextAndSelection, - username, - }); - }; + // const _onApplyUsername = (username) => { + // applyUsername({ + // text: bodyTextRef.current, + // selection: bodySelectionRef.current, + // setTextAndSelection: _setTextAndSelection, + // username, + // }); + // }; const _debouncedOnTextChange = useCallback( debounce(() => { diff --git a/src/components/notification/view/notificationView.tsx b/src/components/notification/view/notificationView.tsx index cf90411e3..6297b1163 100644 --- a/src/components/notification/view/notificationView.tsx +++ b/src/components/notification/view/notificationView.tsx @@ -205,9 +205,8 @@ class NotificationView extends PureComponent { render() { const { isDarkTheme } = this.props; - const { readAllNotification, getActivities, isNotificationRefreshing, intl, isLoading } = - this.props; - const { filters, selectedFilter, selectedIndex } = this.state; + const { readAllNotification, getActivities, isNotificationRefreshing, intl } = this.props; + const { filters, selectedIndex } = this.state; const _notifications = this._getNotificationsArrays(); return ( diff --git a/src/components/organisms/inputSupportModal/container/inputSupportModal.tsx b/src/components/organisms/inputSupportModal/container/inputSupportModal.tsx index 4a68ec003..79082d7e2 100644 --- a/src/components/organisms/inputSupportModal/container/inputSupportModal.tsx +++ b/src/components/organisms/inputSupportModal/container/inputSupportModal.tsx @@ -10,7 +10,7 @@ export interface InputSupportModalProps { children?: any; } -export const InputSupportModal = ({ children, visible, onClose }: InputSupportModalProps, ref) => { +export const InputSupportModal = ({ children, visible, onClose }: InputSupportModalProps) => { const container = useRef(null); const innerContainer = useRef(null); diff --git a/src/components/organisms/quickProfileModal/children/profileBasic.tsx b/src/components/organisms/quickProfileModal/children/profileBasic.tsx index 4f11eccf3..b9ca12fc0 100644 --- a/src/components/organisms/quickProfileModal/children/profileBasic.tsx +++ b/src/components/organisms/quickProfileModal/children/profileBasic.tsx @@ -1,6 +1,5 @@ import React from 'react'; import { View, Text, TouchableOpacity } from 'react-native'; -import FastImage from 'react-native-fast-image'; import * as Progress from 'react-native-progress'; import EStyleSheet from 'react-native-extended-stylesheet'; import { useIntl } from 'react-intl'; diff --git a/src/components/organisms/quickProfileModal/children/quickProfileContent.tsx b/src/components/organisms/quickProfileModal/children/quickProfileContent.tsx index 0722d22b5..c0d61a40a 100644 --- a/src/components/organisms/quickProfileModal/children/quickProfileContent.tsx +++ b/src/components/organisms/quickProfileModal/children/quickProfileContent.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState, useMemo } from 'react'; +import React, { useEffect, useState } from 'react'; import { useIntl } from 'react-intl'; import { View, Alert } from 'react-native'; import { ProfileStats, StatsData } from './profileStats'; diff --git a/src/components/pinAnimatedInput/views/pinAnimatedInputView.js b/src/components/pinAnimatedInput/views/pinAnimatedInputView.js index 927363db1..fc8b92fc6 100644 --- a/src/components/pinAnimatedInput/views/pinAnimatedInputView.js +++ b/src/components/pinAnimatedInput/views/pinAnimatedInputView.js @@ -24,7 +24,7 @@ class PinAnimatedInput extends Component { } _startLoadingAnimation = () => { - [...Array(4)].map((item, index) => { + [...Array(4)].forEach((item, index) => { this.dots[index].setValue(0); }); Animated.sequence([ @@ -44,7 +44,7 @@ class PinAnimatedInput extends Component { }; _stopLoadingAnimation = () => { - [...Array(4)].map((item, index) => { + [...Array(4)].forEach((item, index) => { this.dots[index].stopAnimation(); }); }; @@ -64,7 +64,7 @@ class PinAnimatedInput extends Component { const { pin } = this.props; const marginBottom = []; - [...Array(4)].map((item, index) => { + [...Array(4)].forEach((item, index) => { marginBottom[index] = this.dots[index].interpolate({ inputRange: [0, 0.5, 1], outputRange: [0, 20, 0], diff --git a/src/components/postCard/children/upvoteButton.tsx b/src/components/postCard/children/upvoteButton.tsx index fd1015d6a..bc02a7f6c 100644 --- a/src/components/postCard/children/upvoteButton.tsx +++ b/src/components/postCard/children/upvoteButton.tsx @@ -1,20 +1,17 @@ -import React, { Fragment, useCallback, useEffect, useRef, useState } from 'react'; -import { findNodeHandle, NativeModules, View, TouchableOpacity, Text, Alert } from 'react-native'; +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import { NativeModules, Text, TouchableOpacity, View, findNodeHandle } 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 { isDownVoted as isDownVotedFunc, isVoted as isVotedFunc } from '../../../utils/postParser'; +import { FormattedCurrency } from '../../formatedElements'; import Icon from '../../icon'; import styles from './children.styles'; -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; } diff --git a/src/components/postComments/children/commentsSection.tsx b/src/components/postComments/children/commentsSection.tsx index 83ee3d7a4..75848f56f 100644 --- a/src/components/postComments/children/commentsSection.tsx +++ b/src/components/postComments/children/commentsSection.tsx @@ -4,7 +4,7 @@ import React, { useEffect, useState } from 'react'; import Animated, { SlideInRight } from 'react-native-reanimated'; import { Comment } from '../..'; -export const CommentsSection = ({ item, index, revealReplies, ...props }) => { +export const CommentsSection = ({ item, ...props }) => { const [toggle, setToggle] = useState(item.expandedReplies || false); useEffect(() => { diff --git a/src/components/postElements/body/view/postBodyView.js b/src/components/postElements/body/view/postBodyView.js index 7dab94232..85d7ea211 100644 --- a/src/components/postElements/body/view/postBodyView.js +++ b/src/components/postElements/body/view/postBodyView.js @@ -141,8 +141,7 @@ const PostBody = ({ body, metadata, onLoadEnd, width }) => { const anchoredPostRegex = /(.*?\#\@)(.*)\/(.*)/; const matchedLink = permlink.match(anchoredPostRegex); if (matchedLink) { - author = matchedLink[2]; - permlink = matchedLink[3]; + [, , author, permlink] = matchedLink; } // check if permlink has trailing query param, remove that if is the case diff --git a/src/components/postHtmlRenderer/linkDataParser.ts b/src/components/postHtmlRenderer/linkDataParser.ts index 84493797d..313f5b650 100644 --- a/src/components/postHtmlRenderer/linkDataParser.ts +++ b/src/components/postHtmlRenderer/linkDataParser.ts @@ -57,8 +57,7 @@ export const parseLinkData = (tnode: TNode): LinkData => { const anchoredPostRegex = /(.*?\#\@)(.*)\/(.*)/; const matchedLink = permlink.match(anchoredPostRegex); if (matchedLink) { - author = matchedLink[2]; - permlink = matchedLink[3]; + [, , author, permlink] = matchedLink; } // check if permlink has trailing query param, remove that if is the case diff --git a/src/components/postHtmlRenderer/postHtmlRenderer.tsx b/src/components/postHtmlRenderer/postHtmlRenderer.tsx index 6881e151f..570400bad 100644 --- a/src/components/postHtmlRenderer/postHtmlRenderer.tsx +++ b/src/components/postHtmlRenderer/postHtmlRenderer.tsx @@ -182,8 +182,8 @@ export const PostHtmlRenderer = memo( // remove first child and place it as first separate row in table if (headerIndex !== -1 && colIndex !== -1 && headerIndex < colIndex) { console.log('time to do some switching', headerIndex, colIndex); - const header = child.children[headerIndex]; - const headerRow = new Element('tr', {}, [header]); + // const header = child.children[headerIndex]; + // const headerRow = new Element('tr', {}, [header]); // TODO: put back repalcement for domutils // removeElement(header); diff --git a/src/components/postView/container/postDisplayContainer.tsx b/src/components/postView/container/postDisplayContainer.tsx index 7b25a52d8..3b0132963 100644 --- a/src/components/postView/container/postDisplayContainer.tsx +++ b/src/components/postView/container/postDisplayContainer.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useState } from 'react'; -import { injectIntl, useIntl } from 'react-intl'; +import { useIntl } from 'react-intl'; import get from 'lodash/get'; // Action diff --git a/src/components/postView/view/postDisplayView.tsx b/src/components/postView/view/postDisplayView.tsx index 71a0f61d8..97964cc11 100644 --- a/src/components/postView/view/postDisplayView.tsx +++ b/src/components/postView/view/postDisplayView.tsx @@ -24,12 +24,10 @@ import { showProfileModal, showReplyModal } from '../../../redux/actions/uiActio import { PostTypes } from '../../../constants/postTypes'; import { useUserActivityMutation } from '../../../providers/queries/pointQueries'; import { PointActivityIds } from '../../../providers/ecency/ecency.types'; -import { WriteCommentButton } from '../children/writeCommentButton'; import { PostComments } from '../../postComments'; import { UpvoteButton } from '../../postCard/children/upvoteButton'; import UpvotePopover from '../../upvotePopover'; -const HEIGHT = getWindowDimensions().height; const WIDTH = getWindowDimensions().width; const PostDisplayView = ({ @@ -59,13 +57,12 @@ const PostDisplayView = ({ const postCommentsRef = useRef(null); const upvotePopoverRef = useRef(null); - const [cacheVoteIcrement, setCacheVoteIcrement] = useState(0); + const [cacheVoteIcrement] = useState(0); const [isLoadedComments, setIsLoadedComments] = useState(false); const actionSheet = useRef(null); const [refreshing, setRefreshing] = useState(false); const [postBodyLoading, setPostBodyLoading] = useState(true); const [tags, setTags] = useState([]); - const [postBodyHeight, setPostBodyHeight] = useState(0); // Component Life Cycles useEffect(() => { @@ -259,7 +256,7 @@ const PostDisplayView = ({ ) : ( { - setPostBodyHeight(event.nativeEvent.layout.height); + console.log('content view height', event.nativeEvent.layout.height); }} > {!!post.title && !post.depth ? ( diff --git a/src/components/postsList/container/postsListContainer.tsx b/src/components/postsList/container/postsListContainer.tsx index 261db12cb..5853d06c8 100644 --- a/src/components/postsList/container/postsListContainer.tsx +++ b/src/components/postsList/container/postsListContainer.tsx @@ -7,7 +7,7 @@ import React, { Fragment, useMemo, } from 'react'; -import { FlatListProps, FlatList, RefreshControl, ActivityIndicator, View } from 'react-native'; +import { FlatListProps, 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/profile/children/commentsTabContent.tsx b/src/components/profile/children/commentsTabContent.tsx index 5edd0855d..e9e39e09f 100644 --- a/src/components/profile/children/commentsTabContent.tsx +++ b/src/components/profile/children/commentsTabContent.tsx @@ -109,7 +109,9 @@ const CommentsTabContent = ({ {}} + fetchPost={() => { + console.log('implement fetch if required'); + }} isOwnProfile={isOwnProfile} isHideImage={isHideImage} flatListProps={{ diff --git a/src/components/profile/profileView.js b/src/components/profile/profileView.js index 52c628850..ab46c4b93 100644 --- a/src/components/profile/profileView.js +++ b/src/components/profile/profileView.js @@ -272,10 +272,6 @@ class ProfileView extends PureComponent { ); }; - _isCloseToBottom({ layoutMeasurement, contentOffset, contentSize }) { - return layoutMeasurement.height + contentOffset.y >= contentSize.height - 20; - } - render() { const { handleOnBackPress, quickProfile, reverseHeader, isMuted } = this.props; diff --git a/src/components/qrModal/qrModalView.tsx b/src/components/qrModal/qrModalView.tsx index f93973027..2c6c766e0 100644 --- a/src/components/qrModal/qrModalView.tsx +++ b/src/components/qrModal/qrModalView.tsx @@ -28,9 +28,8 @@ import ROUTES from '../../constants/routeNames'; const hiveuri = require('hive-uri'); const screenHeight = getWindowDimensions().height; -interface QRModalProps {} -export const QRModal = ({}: QRModalProps) => { +export const QRModal = () => { const dispatch = useAppDispatch(); const intl = useIntl(); const isVisibleQRModal = useAppSelector((state) => state.ui.isVisibleQRModal); diff --git a/src/components/quickReplyModal/quickReplyModalContent.tsx b/src/components/quickReplyModal/quickReplyModalContent.tsx index 2829481b4..612a88532 100644 --- a/src/components/quickReplyModal/quickReplyModalContent.tsx +++ b/src/components/quickReplyModal/quickReplyModalContent.tsx @@ -42,7 +42,6 @@ import { export interface QuickReplyModalContentProps { mode: 'comment' | 'wave' | 'post'; selectedPost?: any; - handleCloseRef?: any; onClose: () => void; } diff --git a/src/components/snippetEditorModal/snippetEditorModal.tsx b/src/components/snippetEditorModal/snippetEditorModal.tsx index 02519e35d..e7356e5db 100644 --- a/src/components/snippetEditorModal/snippetEditorModal.tsx +++ b/src/components/snippetEditorModal/snippetEditorModal.tsx @@ -13,7 +13,7 @@ export interface SnippetEditorModalRef { showNewModal: () => void; showEditModal: (snippet: Snippet) => void; } - +// eslint-disable-next-line no-empty-pattern const SnippetEditorModal = ({}, ref) => { const intl = useIntl(); const titleInputRef = useRef(null); diff --git a/src/components/subscribedCommunitiesList/view/subscribedCommunitiesListView.js b/src/components/subscribedCommunitiesList/view/subscribedCommunitiesListView.js index 56e90a65e..c6e9cf5fd 100644 --- a/src/components/subscribedCommunitiesList/view/subscribedCommunitiesListView.js +++ b/src/components/subscribedCommunitiesList/view/subscribedCommunitiesListView.js @@ -57,8 +57,7 @@ const SubscribedCommunitiesListView = ({ - {subscribingCommunities.hasOwnProperty(item[0]) && - subscribingCommunities[item[0]].loading ? ( + {subscribingCommunities[item[0]]?.loading ? ( diff --git a/src/components/tabbedPosts/services/tabbedPostsModels.ts b/src/components/tabbedPosts/services/tabbedPostsModels.ts index e6ee3a0eb..83788bfcc 100644 --- a/src/components/tabbedPosts/services/tabbedPostsModels.ts +++ b/src/components/tabbedPosts/services/tabbedPostsModels.ts @@ -1,5 +1,3 @@ -import { QueryClient } from '@tanstack/react-query'; - export interface TabbedPostsProps { filterOptions: string[]; filterOptionsValue: string[]; diff --git a/src/components/tabbedPosts/view/listEmptyView.tsx b/src/components/tabbedPosts/view/listEmptyView.tsx index 12a4e7629..38965363e 100644 --- a/src/components/tabbedPosts/view/listEmptyView.tsx +++ b/src/components/tabbedPosts/view/listEmptyView.tsx @@ -78,7 +78,7 @@ const TabEmptyView = ({ filterKey, isNoPost }: TabEmptyViewProps) => { useEffect(() => { const recommendeds = [...recommendedCommunities]; - Object.keys(subscribingCommunities).map((communityId) => { + Object.keys(subscribingCommunities).forEach((communityId) => { if (!subscribingCommunities[communityId].loading) { if (!subscribingCommunities[communityId].error) { if (subscribingCommunities[communityId].isSubscribed) { @@ -104,7 +104,7 @@ const TabEmptyView = ({ filterKey, isNoPost }: TabEmptyViewProps) => { useEffect(() => { const recommendeds = [...recommendedUsers]; - Object.keys(followingUsers).map((following) => { + Object.keys(followingUsers).forEach((following) => { if (!followingUsers[following].loading) { if (!followingUsers[following].error) { if (followingUsers[following].isFollowing) { @@ -262,9 +262,7 @@ const TabEmptyView = ({ filterKey, isNoPost }: TabEmptyViewProps) => { rightTextStyle={[styles.followText, item.isFollowing && styles.unfollowText]} isLoggedIn={isLoggedIn} isFollowing={item.isFollowing} - isLoadingRightAction={ - followingUsers.hasOwnProperty(item._id) && followingUsers[item._id].loading - } + isLoadingRightAction={followingUsers[item._id]?.loading} onPressRightText={_handleFollowUserButtonPress} handleOnPress={(username) => navigation.navigate({ @@ -311,10 +309,7 @@ const TabEmptyView = ({ filterKey, isNoPost }: TabEmptyViewProps) => { } handleSubscribeButtonPress={_handleSubscribeCommunityButtonPress} isSubscribed={item.isSubscribed} - isLoadingRightAction={ - subscribingCommunities.hasOwnProperty(item.name) && - subscribingCommunities[item.name].loading - } + isLoadingRightAction={subscribingCommunities[item.name]?.loading} isLoggedIn={isLoggedIn} /> )} diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index f2b5c99e9..92f905931 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -192,6 +192,7 @@ export const UploadsGalleryModal = forwardRef( for (let i = 0; i < media.length; i++) { const element = media[i]; if (element.mime === 'image/heic') { + // eslint-disable-next-line no-await-in-loop const res = await RNHeicConverter.convert({ path: element.sourceURL }); // default with quality = 1 & jpg extension if (res && res.path) { element.mime = 'image/jpeg'; @@ -225,6 +226,7 @@ export const UploadsGalleryModal = forwardRef( for (let index = 0; index < media.length; index++) { const element = media[index]; if (element) { + // eslint-disable-next-line no-await-in-loop await _uploadImage(element, { shouldInsert }); } } @@ -386,7 +388,8 @@ export const UploadsGalleryModal = forwardRef( // inserts media items in post body const _insertMedia = async (map: Map) => { const data: MediaInsertData[] = []; - for (const index of map.keys()) { + + map.forEach((value, index) => { console.log(index); const item:MediaItem = mediaUploadsQuery.data[index]; data.push({ @@ -395,7 +398,8 @@ export const UploadsGalleryModal = forwardRef( status: MediaInsertStatus.READY, mode }); - } + }); + handleMediaInsert(data); }; diff --git a/src/containers/inAppPurchaseContainer.tsx b/src/containers/inAppPurchaseContainer.tsx index 5c59f210d..ddb20246b 100644 --- a/src/containers/inAppPurchaseContainer.tsx +++ b/src/containers/inAppPurchaseContainer.tsx @@ -166,6 +166,7 @@ class InAppPurchaseContainer extends Component { if (_purchase.productId !== '999accounts') { // consume item using finishTransactionx + // eslint-disable-next-line no-await-in-loop await this._consumePurchase(purchases[i]); } } diff --git a/src/providers/hive/dhive.js b/src/providers/hive/dhive.js index 450f4de1b..18a8a1f4d 100644 --- a/src/providers/hive/dhive.js +++ b/src/providers/hive/dhive.js @@ -410,50 +410,49 @@ export const getUser = async (user, loggedIn = true) => { const cache = {}; const patt = /hive-\d\w+/g; -export const getCommunity = async (tag, observer = '') => - new Promise(async (resolve, reject) => { +export const getCommunity = async (tag, observer = '') => { + try { + const community = await client.call('bridge', 'get_community', { + name: tag, + observer, + }); + if (community) { + return community; + } else { + return {}; + } + } catch (err) { + bugsnagInstance.notify('failed to get community', err); + throw err; + } +}; + +export const getCommunityTitle = async (tag) => { + if (cache[tag] !== undefined) { + return cache[tag]; + } + const mm = tag.match(patt); + if (mm && mm.length > 0) { try { const community = await client.call('bridge', 'get_community', { name: tag, - observer, + observer: '', }); if (community) { - resolve(community); + const { title } = community; + cache[tag] = title; + return title; } else { - resolve({}); + return tag; } - } catch (error) { - reject(error); + } catch (err) { + bugsnagInstance.notify('failed to get community title'); + throw err; } - }); - -export const getCommunityTitle = async (tag) => - new Promise(async (resolve, reject) => { - if (cache[tag] !== undefined) { - resolve(cache[tag]); - return; - } - const mm = tag.match(patt); - if (mm && mm.length > 0) { - try { - const community = await client.call('bridge', 'get_community', { - name: tag, - observer: '', - }); - if (community) { - const { title } = community; - cache[tag] = title; - resolve(title); - } else { - resolve(tag); - } - } catch (error) { - reject(error); - } - } - - resolve(tag); - }); + } else { + return tag; + } +}; export const getCommunities = async ( last = '', @@ -461,43 +460,43 @@ export const getCommunities = async ( query = null, sort = 'rank', observer = '', -) => - new Promise(async (resolve, reject) => { - try { - console.log('Getting communities', query); - const data = await client.call('bridge', 'list_communities', { - last, - limit, - query, - sort, - observer, - }); - if (data) { - resolve(data); - } else { - resolve({}); - } - } catch (error) { - console.log(error); - resolve({}); +) => { + try { + console.log('Getting communities', query); + const data = await client.call('bridge', 'list_communities', { + last, + limit, + query, + sort, + observer, + }); + if (data) { + return data; + } else { + return {}; } - }); + } catch (error) { + console.warn('failed to get communities', error); + bugsnagInstance.notify('failed to get communities', error); + return {}; + } +}; -export const getSubscriptions = (account = '') => - new Promise(async (resolve, reject) => { - try { - const data = await client.call('bridge', 'list_all_subscriptions', { - account, - }); - if (data) { - resolve(data); - } else { - resolve({}); - } - } catch (error) { - reject(error); +export const getSubscriptions = async (account = '') => { + try { + const data = await client.call('bridge', 'list_all_subscriptions', { + account, + }); + if (data) { + return data; + } else { + return {}; } - }); + } catch (error) { + bugsnagInstance.notify('failed to get subscriptions', error); + throw error; + } +}; // TODO: Move to utils folder export const vestToSteem = async (vestingShares, totalVestingShares, totalVestingFundSteem) => @@ -2133,7 +2132,6 @@ export const getActiveKey = (local, pin) => { }; export const votingPower = (account) => { - // @ts-ignore "Account" is compatible with dhive's "ExtendedAccount" const calc = client.rc.calculateVPMana(account); const { percentage } = calc; diff --git a/src/providers/queries/draftQueries.ts b/src/providers/queries/draftQueries.ts index 9b60bac4f..b7b374a74 100644 --- a/src/providers/queries/draftQueries.ts +++ b/src/providers/queries/draftQueries.ts @@ -60,8 +60,9 @@ export const useDraftsBatchDeleteMutation = () => { return useMutation( async (deleteIds) => { console.log('deleteIds : ', JSON.stringify(deleteIds, null, 2)); - + // eslint-disable-next-line for (const i in deleteIds) { + // eslint-disable-next-line await deleteDraft(deleteIds[i]); } return deleteIds; @@ -103,7 +104,9 @@ export const useSchedulesBatchDeleteMutation = () => { async (deleteIds) => { console.log('deleteIds : ', JSON.stringify(deleteIds, null, 2)); + // eslint-disable-next-line for (const i in deleteIds) { + // eslint-disable-next-line await deleteScheduledPost(deleteIds[i]); } return deleteIds; diff --git a/src/providers/queries/editorQueries.ts b/src/providers/queries/editorQueries.ts index 203550347..6bf4eca55 100644 --- a/src/providers/queries/editorQueries.ts +++ b/src/providers/queries/editorQueries.ts @@ -242,7 +242,9 @@ export const useMediaDeleteMutation = () => { const intl = useIntl(); return useMutation( async (deleteIds) => { + // eslint-disable-next-line no-restricted-syntax for (const i in deleteIds) { + // eslint-disable-next-line no-await-in-loop await deleteImage(deleteIds[i]); } return deleteIds; diff --git a/src/screens/assetDetails/children/activitiesList.tsx b/src/screens/assetDetails/children/activitiesList.tsx index 282f25daf..0ce5293d5 100644 --- a/src/screens/assetDetails/children/activitiesList.tsx +++ b/src/screens/assetDetails/children/activitiesList.tsx @@ -23,7 +23,7 @@ interface ActivitiesListProps { onActionPress: (transferType: string, extraParams?: any) => void; } -const ActivitiesList = ({ +export const ActivitiesList = ({ header, loading, refreshing, @@ -129,5 +129,3 @@ const ActivitiesList = ({ /> ); }; - -export default ActivitiesList; diff --git a/src/screens/assetDetails/screen/assetDetailsScreen.tsx b/src/screens/assetDetails/screen/assetDetailsScreen.tsx index 058c631eb..88fd57dbe 100644 --- a/src/screens/assetDetails/screen/assetDetailsScreen.tsx +++ b/src/screens/assetDetails/screen/assetDetailsScreen.tsx @@ -5,7 +5,7 @@ import { gestureHandlerRootHOC } from 'react-native-gesture-handler'; import { BasicHeader } from '../../../components'; import { CoinSummary } from '../children'; import styles from './screen.styles'; -import ActivitiesList from '../children/activitiesList'; +import { ActivitiesList } from '../children'; import { CoinActivity, CoinData, QuoteItem } from '../../../redux/reducers/walletReducer'; import { useAppSelector } from '../../../hooks'; import RootNavigation from '../../../navigation/rootNavigation'; From 9ced38724b5b5052cd7a2b3a119367fefb0e5230 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 3 Nov 2023 16:27:24 +0500 Subject: [PATCH 047/111] all lint errors resolved --- package.json | 6 ++++-- src/components/markdownEditor/view/markdownEditorView.tsx | 4 +--- src/components/notification/view/notificationView.tsx | 3 +-- .../notificationLine/view/notificationLineView.js | 3 +-- .../headerDescription/view/postHeaderDescription.js | 3 +-- src/components/postsList/container/postsListContainer.tsx | 5 ++--- src/components/qrModal/qrModalView.tsx | 3 +-- src/components/sideMenu/view/sideMenuView.js | 2 +- src/components/userAvatar/view/userAvatarView.tsx | 2 +- src/providers/hive/dhive.js | 4 ++-- src/redux/store/store.ts | 1 + src/screens/follows/screen/followsScreen.js | 6 ++---- src/utils/createIntl.js | 1 + yarn.lock | 2 +- 14 files changed, 20 insertions(+), 25 deletions(-) diff --git a/package.json b/package.json index e6c8e4181..c1669dfd8 100644 --- a/package.json +++ b/package.json @@ -17,8 +17,8 @@ "releasenotes": "./release-notes.sh > release-notes.txt; node -e 'console.log(JSON.stringify(require(\"fs\").readFileSync(\"release-notes.txt\", \"utf8\")));' > release-notes.json", "test": "node node_modules/jest/bin/jest.js --watch", "lint": "eslint src/ --ext .js,.jsx,.ts,.tsx", - "lint:fix": "eslint src/ --fix --ext .js,.jsx,.ts,.tsx", - "format": "prettier --write 'src/**/*.{js,jsx,ts,tsx}' && yarn lint:fix --fix", + "lint:fix": "eslint src/ --fix --quiet --ext .js,.jsx,.ts,.tsx", + "format": "prettier --write 'src/**/*.{js,jsx,ts,tsx}' && yarn lint:fix", "lint-staged": "lint-staged", "clear": "watchman watch-del-all && rm -rf $TMPDIR/react-native-packager-cache-* && rm -rf $TMPDIR/metro-bundler-cache-* && rm -rf node_modules/ && yarn && yarn start -- --reset-cache", "bump-patch": "npm version patch --no-git-tag-version", @@ -166,10 +166,12 @@ "react-navigation-redux-helpers": "^4.0.1", "react-redux": "^8.0.4", "readable-stream": "1.0.33", + "redux": "^4.2.1", "redux-flipper": "^2.0.2", "redux-persist": "^6.0.0", "redux-persist-filesystem-storage": "^4.1.0", "redux-promise": "^0.6.0", + "redux-thunk": "^2.4.2", "rn-fetch-blob": "^0.12.0", "rn-placeholder": "^1.3.2", "rtl-detect": "^1.0.4", diff --git a/src/components/markdownEditor/view/markdownEditorView.tsx b/src/components/markdownEditor/view/markdownEditorView.tsx index a78fc774c..020bf4df1 100644 --- a/src/components/markdownEditor/view/markdownEditorView.tsx +++ b/src/components/markdownEditor/view/markdownEditorView.tsx @@ -40,8 +40,6 @@ import applySnippet from '../children/formats/applySnippet'; import { MainButton } from '../../mainButton'; import isAndroidOreo from '../../../utils/isAndroidOreo'; import { OptionsModal } from '../../atoms'; -// import { UsernameAutofillBar } from '../children/usernameAutofillBar'; -import applyUsername from '../children/formats/applyUsername'; import { walkthrough } from '../../../redux/constants/walkthroughConstants'; import { MediaInsertData } from '../../uploadsGalleryModal/container/uploadsGalleryModal'; import { EditorToolbar } from '../children/editorToolbar'; @@ -183,7 +181,7 @@ const MarkdownEditorView = ({ // applyUsername({ // text: bodyTextRef.current, // selection: bodySelectionRef.current, - // setTextAndSelection: _setTextAndSelection, + // setTextAndSelection: _setTextAndSelection,x // username, // }); // }; diff --git a/src/components/notification/view/notificationView.tsx b/src/components/notification/view/notificationView.tsx index 6297b1163..d9ab24a2e 100644 --- a/src/components/notification/view/notificationView.tsx +++ b/src/components/notification/view/notificationView.tsx @@ -37,7 +37,6 @@ class NotificationView extends PureComponent { { key: 'mentions', value: 'MENTIONS' }, // { key: 'reblogs', value: 'REBLOGS' }, ], - selectedFilter: 'activities', selectedIndex: 0, }; this.listRef = React.createRef(); @@ -53,7 +52,7 @@ class NotificationView extends PureComponent { const _selectedFilter = filters[index].key; - this.setState({ selectedFilter: _selectedFilter, selectedIndex: index, contentOffset }); + this.setState({ selectedIndex: index, contentOffset }); await changeSelectedFilter(_selectedFilter, index); this.listRef.current?.scrollToOffset({ x: 0, y: 0, animated: false }); }; diff --git a/src/components/notificationLine/view/notificationLineView.js b/src/components/notificationLine/view/notificationLineView.js index 7bc95ff4e..0d925613e 100644 --- a/src/components/notificationLine/view/notificationLineView.js +++ b/src/components/notificationLine/view/notificationLineView.js @@ -20,7 +20,6 @@ const NotificationLineView = ({ }) => { const [isRead, setIsRead] = useState(notification.read); const intl = useIntl(); - let _title; let titleExtra = ''; let _moreinfo = ''; useEffect(() => { @@ -54,7 +53,7 @@ const NotificationLineView = ({ titleExtra = _percent; } - _title = `${titleExtra} ${intl.formatMessage({ + const _title = `${titleExtra} ${intl.formatMessage({ id: `notification.${notification.type}`, })}`; diff --git a/src/components/postElements/headerDescription/view/postHeaderDescription.js b/src/components/postElements/headerDescription/view/postHeaderDescription.js index f8f59b600..0b047ce12 100644 --- a/src/components/postElements/headerDescription/view/postHeaderDescription.js +++ b/src/components/postElements/headerDescription/view/postHeaderDescription.js @@ -14,7 +14,7 @@ import { IconButton } from '../../..'; import RootNavigation from '../../../../navigation/rootNavigation'; // Constants -const DEFAULT_IMAGE = require('../../../../assets/ecency.png'); +import DEFAULT_IMAGE from '../../../../assets/ecency.png'; class PostHeaderDescription extends PureComponent { // Component Life Cycles @@ -88,7 +88,6 @@ class PostHeaderDescription extends PureComponent { secondaryContentComponent, showDotMenuButton, handleOnDotPress, - isPinned, } = this.props; return ( diff --git a/src/components/postsList/container/postsListContainer.tsx b/src/components/postsList/container/postsListContainer.tsx index 5853d06c8..edb4759d4 100644 --- a/src/components/postsList/container/postsListContainer.tsx +++ b/src/components/postsList/container/postsListContainer.tsx @@ -144,8 +144,7 @@ const postsListContainer = ( const _updateReblogsCollection = async () => { // improve routine using list or promises - for (const i in data) { - const _item = data[i]; + data.forEach(async (_item) => { const _postPath = _item.author + _item.permlink; if (!reblogsCollectionRef.current[_postPath]) { try { @@ -159,7 +158,7 @@ const postsListContainer = ( reblogsCollectionRef.current = { ...reblogsCollectionRef.current, [_postPath]: [] }; } } - } + }); }; const _setImageRatioInMap = (mapKey: string, height: number) => { diff --git a/src/components/qrModal/qrModalView.tsx b/src/components/qrModal/qrModalView.tsx index 2c6c766e0..b748239f4 100644 --- a/src/components/qrModal/qrModalView.tsx +++ b/src/components/qrModal/qrModalView.tsx @@ -6,6 +6,7 @@ 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 * as hiveuri from 'hive-uri'; import styles from './qrModalStyles'; import { useAppDispatch, useAppSelector } from '../../hooks'; import { @@ -25,8 +26,6 @@ import authType from '../../constants/authType'; import { delay } from '../../utils/editor'; import ROUTES from '../../constants/routeNames'; -const hiveuri = require('hive-uri'); - const screenHeight = getWindowDimensions().height; export const QRModal = () => { diff --git a/src/components/sideMenu/view/sideMenuView.js b/src/components/sideMenu/view/sideMenuView.js index ed4042448..398e763a9 100644 --- a/src/components/sideMenu/view/sideMenuView.js +++ b/src/components/sideMenu/view/sideMenuView.js @@ -32,7 +32,7 @@ import styles from './sideMenuStyles'; import { showActionModal, toggleQRModal } from '../../../redux/actions/uiAction'; // Images -const SIDE_MENU_BACKGROUND = require('../../../assets/side_menu_background.png'); +import SIDE_MENU_BACKGROUND from '../../../assets/side_menu_background.png'; const SideMenuView = ({ currentAccount, diff --git a/src/components/userAvatar/view/userAvatarView.tsx b/src/components/userAvatar/view/userAvatarView.tsx index 618d8a8ed..132eb905c 100644 --- a/src/components/userAvatar/view/userAvatarView.tsx +++ b/src/components/userAvatar/view/userAvatarView.tsx @@ -14,7 +14,7 @@ import ROUTES from '../../../constants/routeNames'; import { useAppSelector } from '../../../hooks'; import { getResizedAvatar } from '../../../utils/image'; -const DEFAULT_IMAGE = require('../../../assets/avatar_default.png'); +import DEFAULT_IMAGE from '../../../assets/avatar_default.png'; /* Props * ------------------------------------------------f diff --git a/src/providers/hive/dhive.js b/src/providers/hive/dhive.js index 18a8a1f4d..d7808a93a 100644 --- a/src/providers/hive/dhive.js +++ b/src/providers/hive/dhive.js @@ -18,6 +18,7 @@ import { createHash } from 'react-native-crypto'; import { Client as hsClient } from 'hivesigner'; import Config from 'react-native-config'; import { get, has } from 'lodash'; +import * as hiveuri from 'hive-uri'; import { getServer, getCache, setCache } from '../../realm/realm'; // Utils @@ -44,7 +45,7 @@ import bugsnagInstance from '../../config/bugsnag'; import bugsnapInstance from '../../config/bugsnag'; import TransferTypes from '../../constants/transferTypes'; -const hiveuri = require('hive-uri'); +// eslint-disable-next-line @typescript-eslint/no-var-requires global.Buffer = global.Buffer || require('buffer').Buffer; const DEFAULT_SERVER = SERVER_LIST; @@ -2145,7 +2146,6 @@ export const resolveTransaction = async (parsedTx, parsedParams, signer) => { // resolve the decoded tx and params to a signable tx const { tx } = hiveuri.resolveTransaction(parsedTx, parsedParams, { - /* eslint-disable no-bitwise */ ref_block_num: props.head_block_number & 0xffff, ref_block_prefix: Buffer.from(props.head_block_id, 'hex').readUInt32LE(4), expiration: new Date(Date.now() + client.broadcast.expireTime + EXPIRE_TIME) diff --git a/src/redux/store/store.ts b/src/redux/store/store.ts index 126445777..899c2a9a0 100644 --- a/src/redux/store/store.ts +++ b/src/redux/store/store.ts @@ -51,6 +51,7 @@ const middleware = [thunk]; let enhancers; if (__DEV__) { + // eslint-disable-next-line @typescript-eslint/no-var-requires const createDebugger = require('redux-flipper').default; middleware.push(createDebugger()); enhancers = compose(applyMiddleware(...middleware), Reactotron.createEnhancer()); diff --git a/src/screens/follows/screen/followsScreen.js b/src/screens/follows/screen/followsScreen.js index 461038f91..9903a6224 100644 --- a/src/screens/follows/screen/followsScreen.js +++ b/src/screens/follows/screen/followsScreen.js @@ -1,11 +1,9 @@ -/* eslint-disable react/jsx-wrap-multilines */ import React, { PureComponent } from 'react'; -import { View, Text, FlatList, ActivityIndicator } from 'react-native'; import { injectIntl } from 'react-intl'; +import { ActivityIndicator, FlatList, Text, View } from 'react-native'; // Constants -import { useNavigation } from '@react-navigation/native'; import EStyleSheet from 'react-native-extended-stylesheet'; -import { useDispatch, connect } from 'react-redux'; +import { connect } from 'react-redux'; import { showProfileModal } from '../../../redux/actions/uiAction'; // Components import { BasicHeader, UserListItem } from '../../../components'; diff --git a/src/utils/createIntl.js b/src/utils/createIntl.js index 247494151..77e616034 100644 --- a/src/utils/createIntl.js +++ b/src/utils/createIntl.js @@ -3,6 +3,7 @@ import { flattenMessages } from './flattenMessages'; import messages from '../config/locales'; const _createIntl = () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires const store = require('../redux/store/store'); const state = store.store.getState(); diff --git a/yarn.lock b/yarn.lock index 5886f0383..035c0c25f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -9685,7 +9685,7 @@ redux-thunk@^2.4.2: resolved "https://registry.yarnpkg.com/redux-thunk/-/redux-thunk-2.4.2.tgz#b9d05d11994b99f7a91ea223e8b04cf0afa5ef3b" integrity sha512-+P3TjtnP0k/FEjcBL5FZpoovtvrTNT/UXd4/sluaSyrURlSlhLSzEdfsTBW7WsKB6yPvgd7q/iZPICFjW4o57Q== -redux@^4.0.0, redux@^4.2.0: +redux@^4.0.0, redux@^4.2.0, redux@^4.2.1: version "4.2.1" resolved "https://registry.yarnpkg.com/redux/-/redux-4.2.1.tgz#c08f4306826c49b5e9dc901dee0452ea8fce6197" integrity sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w== From 5f947e819e15297749e39d1c1e8fbeadd9777398 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 3 Nov 2023 16:28:12 +0500 Subject: [PATCH 048/111] put back pre-commit hook --- package.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/package.json b/package.json index c1669dfd8..f974a3c20 100644 --- a/package.json +++ b/package.json @@ -225,6 +225,11 @@ "git add" ] }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, "jest": { "preset": "react-native" }, From ff614845c7a9602fbd98917f0893f4d8231c269d Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 3 Nov 2023 16:30:44 +0500 Subject: [PATCH 049/111] update lint:fix command --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index f974a3c20..40cac43b3 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "releasenotes": "./release-notes.sh > release-notes.txt; node -e 'console.log(JSON.stringify(require(\"fs\").readFileSync(\"release-notes.txt\", \"utf8\")));' > release-notes.json", "test": "node node_modules/jest/bin/jest.js --watch", "lint": "eslint src/ --ext .js,.jsx,.ts,.tsx", - "lint:fix": "eslint src/ --fix --quiet --ext .js,.jsx,.ts,.tsx", + "lint:fix": "eslint src/ --fix --quiet", "format": "prettier --write 'src/**/*.{js,jsx,ts,tsx}' && yarn lint:fix", "lint-staged": "lint-staged", "clear": "watchman watch-del-all && rm -rf $TMPDIR/react-native-packager-cache-* && rm -rf $TMPDIR/metro-bundler-cache-* && rm -rf node_modules/ && yarn && yarn start -- --reset-cache", From 90a82b008f5443b8ea529ffadb3754d2325c7c43 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 3 Nov 2023 16:39:12 +0500 Subject: [PATCH 050/111] import clean up --- src/screens/assetDetails/screen/assetDetailsScreen.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/screens/assetDetails/screen/assetDetailsScreen.tsx b/src/screens/assetDetails/screen/assetDetailsScreen.tsx index 88fd57dbe..6f6e59418 100644 --- a/src/screens/assetDetails/screen/assetDetailsScreen.tsx +++ b/src/screens/assetDetails/screen/assetDetailsScreen.tsx @@ -3,9 +3,8 @@ import React, { useEffect, useRef, useState } from 'react'; import { useIntl } from 'react-intl'; import { gestureHandlerRootHOC } from 'react-native-gesture-handler'; import { BasicHeader } from '../../../components'; -import { CoinSummary } from '../children'; +import { CoinSummary, ActivitiesList } from '../children'; import styles from './screen.styles'; -import { ActivitiesList } from '../children'; import { CoinActivity, CoinData, QuoteItem } from '../../../redux/reducers/walletReducer'; import { useAppSelector } from '../../../hooks'; import RootNavigation from '../../../navigation/rootNavigation'; From 773bd4c4219954f531811d52b044e1c1a15cb0d8 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Tue, 14 Nov 2023 14:09:55 +0500 Subject: [PATCH 051/111] lint fix --- .../markdownEditor/children/editorToolbar.tsx | 23 +- .../children/uploadsGalleryContent.tsx | 4 +- .../container/uploadsGalleryModal.tsx | 46 ++- src/navigation/stackNavigator.tsx | 7 +- src/providers/queries/editorQueries.ts | 118 ++++--- src/providers/queries/queryKeys.ts | 2 +- src/providers/speak/constants.ts | 14 +- src/providers/speak/converters.ts | 7 +- src/providers/speak/speak.ts | 302 +++++++++--------- src/providers/speak/speak.types.ts | 102 +++--- src/screens/editor/children/styles.ts | 1 - .../editor/container/editorContainer.tsx | 4 +- 12 files changed, 304 insertions(+), 326 deletions(-) diff --git a/src/components/markdownEditor/children/editorToolbar.tsx b/src/components/markdownEditor/children/editorToolbar.tsx index 60d53aab0..b2630fbd2 100644 --- a/src/components/markdownEditor/children/editorToolbar.tsx +++ b/src/components/markdownEditor/children/editorToolbar.tsx @@ -57,7 +57,7 @@ export const EditorToolbar = ({ setKeyboardVisible(false); // or some other action }); - //TODO: set to false before PR + // TODO: set to false before PR _showUploadsExtension(); return () => { @@ -81,32 +81,29 @@ export const EditorToolbar = ({ ); - - const _showUploadsExtension = (mode:Modes) => { - - if(!uploadsGalleryModalRef.current){ + const _showUploadsExtension = (mode: Modes) => { + if (!uploadsGalleryModalRef.current) { return; } - + const _curMode = uploadsGalleryModalRef.current.getMode(); - if (!isExtensionVisible || _curMode !== mode){ + if (!isExtensionVisible || _curMode !== mode) { uploadsGalleryModalRef.current.toggleModal(true, mode); _revealExtension(); return; } - _hideExtension() - + _hideExtension(); }; const _showImageUploads = () => { - _showUploadsExtension(Modes.MODE_IMAGE) - } + _showUploadsExtension(Modes.MODE_IMAGE); + }; const _showVideoUploads = () => { - _showUploadsExtension(Modes.MODE_VIDEO) - } + _showUploadsExtension(Modes.MODE_VIDEO); + }; // handles extension closing const _onGestureEvent = Animated.event( diff --git a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx index 82d51c378..38ed3a9b3 100644 --- a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx +++ b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx @@ -116,7 +116,9 @@ const UploadsGalleryContent = ({ } }; - const thumbUrl = item.thumbUrl || proxifyImageSrc(item.url, 600, 500, Platform.OS === 'ios' ? 'match' : 'webp'); + const thumbUrl = + item.thumbUrl || + proxifyImageSrc(item.url, 600, 500, Platform.OS === 'ios' ? 'match' : 'webp'); let isInsertedTimes = 0; insertedMediaUrls?.forEach((url) => (isInsertedTimes += url === item.url ? 1 : 0)); const isToBeDeleted = deleteIds.indexOf(item._id) >= 0; diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 92f905931..6de72f160 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -1,4 +1,11 @@ -import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'; +import React, { + forwardRef, + useEffect, + useImperativeHandle, + useMemo, + useRef, + useState, +} from 'react'; import { useIntl } from 'react-intl'; import { Alert, AlertButton } from 'react-native'; import ImagePicker, { Image } from 'react-native-image-crop-picker'; @@ -10,7 +17,11 @@ import UploadsGalleryContent from '../children/uploadsGalleryContent'; import { useAppDispatch, useAppSelector } from '../../../hooks'; import { delay, extractFilenameFromPath } from '../../../utils/editor'; import showLoginAlert from '../../../utils/showLoginAlert'; -import { useMediaQuery, useMediaUploadMutation, useVideoUploadsQuery } from '../../../providers/queries'; +import { + useMediaQuery, + useMediaUploadMutation, + useVideoUploadsQuery, +} from '../../../providers/queries'; import { showActionModal } from '../../../redux/actions/uiAction'; import { MediaItem } from '../../../providers/ecency/ecency.types'; @@ -18,10 +29,9 @@ export interface UploadsGalleryModalRef { showModal: () => void; } - export enum Modes { MODE_IMAGE = 0, - MODE_VIDEO = 1 + MODE_VIDEO = 1, } export enum MediaInsertStatus { @@ -38,12 +48,9 @@ export interface MediaInsertData { mode: Modes; } - - interface UploadsGalleryModalProps { insertedMediaUrls: string[]; paramFiles: any[]; - username: string; isEditing: boolean; isPreviewActive: boolean; allowMultiple?: boolean; @@ -57,7 +64,6 @@ export const UploadsGalleryModal = forwardRef( { insertedMediaUrls, paramFiles, - username, isEditing, isPreviewActive, allowMultiple, @@ -73,24 +79,20 @@ export const UploadsGalleryModal = forwardRef( const imageUploadsQuery = useMediaQuery(); const videoUploadsQuery = useVideoUploadsQuery(); - - const mediaUploadMutation = useMediaUploadMutation(); const pendingInserts = useRef([]); const [showModal, setShowModal] = useState(false); const [isAddingToUploads, setIsAddingToUploads] = useState(false); - const [mode, setMode] = useState(Modes.MODE_IMAGE) + const [mode, setMode] = useState(Modes.MODE_IMAGE); const isLoggedIn = useAppSelector((state) => state.application.isLoggedIn); const mediaUploadsQuery = useMemo( - ()=> mode === Modes.MODE_VIDEO ? videoUploadsQuery : imageUploadsQuery , [mode]) - - - const pinCode = useAppSelector((state) => state.application.pin); - const currentAccount = useAppSelector((state) => state.account.currentAccount); + () => (mode === Modes.MODE_VIDEO ? videoUploadsQuery : imageUploadsQuery), + [mode], + ); useImperativeHandle(ref, () => ({ toggleModal: (value: boolean, _mode: Modes = mode) => { @@ -107,9 +109,8 @@ export const UploadsGalleryModal = forwardRef( _getMediaUploads(_mode); } - setMode(_mode) + setMode(_mode); setShowModal(value); - }, getMode: () => mode, })); @@ -138,8 +139,6 @@ export const UploadsGalleryModal = forwardRef( } }, [paramFiles]); - - useEffect(() => { if (!isEditing && pendingInserts.current.length) { handleMediaInsert(pendingInserts.current); @@ -247,8 +246,6 @@ export const UploadsGalleryModal = forwardRef( setIsAddingToUploads(true); } - - await mediaUploadMutation.mutateAsync( { media, @@ -277,8 +274,6 @@ export const UploadsGalleryModal = forwardRef( }, }, ); - - } catch (error) { console.log('error while uploading image : ', error); @@ -378,7 +373,6 @@ export const UploadsGalleryModal = forwardRef( const _getMediaUploads = async (_mode: Modes = mode) => { try { mediaUploadsQuery.refetch(); - } catch (err) { console.warn('Failed to get images'); } @@ -396,7 +390,7 @@ export const UploadsGalleryModal = forwardRef( url: mode === Modes.MODE_VIDEO ? (item.speakData?._id || '') : item.url, text: mode === Modes.MODE_VIDEO ? `3speak` : '', status: MediaInsertStatus.READY, - mode + mode, }); }); diff --git a/src/navigation/stackNavigator.tsx b/src/navigation/stackNavigator.tsx index 411135438..5d32c2530 100644 --- a/src/navigation/stackNavigator.tsx +++ b/src/navigation/stackNavigator.tsx @@ -43,9 +43,12 @@ const RootStack = createNativeStackNavigator(); const MainStack = createNativeStackNavigator(); const MainStackNavigator = () => { - //TODO: remove initialRoute before PR + // TODO: remove initialRoute before PR return ( - + diff --git a/src/providers/queries/editorQueries.ts b/src/providers/queries/editorQueries.ts index 6bf4eca55..2355ceef6 100644 --- a/src/providers/queries/editorQueries.ts +++ b/src/providers/queries/editorQueries.ts @@ -1,6 +1,9 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useIntl } from 'react-intl'; import { Image } from 'react-native-image-crop-picker'; +import Upload, { UploadOptions } from 'react-native-background-upload'; +import Config from 'react-native-config'; +import { Platform } from 'react-native'; import { useAppDispatch, useAppSelector } from '../../hooks'; import { toastNotification } from '../../redux/actions/uiAction'; import { @@ -11,16 +14,13 @@ import { getFragments, getImages, updateFragment, - uploadImage, } from '../ecency/ecency'; import { MediaItem, Snippet } from '../ecency/ecency.types'; import { signImage } from '../hive/dhive'; import QUERIES from './queryKeys'; -import Upload, { UploadOptions } from 'react-native-background-upload' -import Config from 'react-native-config'; -import { Platform } from 'react-native'; import { getAllVideoStatuses } from '../speak/speak'; import { ThreeSpeakVideo } from '../speak/speak.types'; +import bugsnapInstance from '../../config/bugsnag'; interface SnippetMutationVars { id: string | null; @@ -80,15 +80,14 @@ export const useAddToUploadsMutation = () => { }); }; - export const useVideoUploadsQuery = () => { const intl = useIntl(); const dispatch = useAppDispatch(); - const currentAccount = useAppSelector(state => state.account.currentAccount); - const pinHash = useAppSelector(state => state.application.pin); + const currentAccount = useAppSelector((state) => state.account.currentAccount); + const pinHash = useAppSelector((state) => state.application.pin); - const _fetchVideoUploads = async () => await getAllVideoStatuses(currentAccount, pinHash); + const _fetchVideoUploads = async () => getAllVideoStatuses(currentAccount, pinHash); return useQuery([QUERIES.MEDIA.GET_VIDEOS], _fetchVideoUploads, { initialData: [], @@ -96,7 +95,7 @@ export const useVideoUploadsQuery = () => { dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); }, }); -} +}; export const useMediaUploadMutation = () => { const intl = useIntl(); @@ -107,66 +106,61 @@ export const useMediaUploadMutation = () => { const currentAccount = useAppSelector((state) => state.account.currentAccount); const pinCode = useAppSelector((state) => state.application.pin); - const _uploadMedia = ({ media }: MediaUploadVars) => { + const _uploadMedia = async ({ media }: MediaUploadVars) => { + try { + const sign = await signImage(media, currentAccount, pinCode); - return new Promise(async (resolve, reject) => { + const _options: UploadOptions = { + url: `${Config.NEW_IMAGE_API}/hs/${sign}`, + path: Platform.select({ + ios: `file://${media.path}`, + android: media.path.replace('file://', ''), + }), + method: 'POST', + type: 'multipart', + maxRetries: 2, // set retry count (Android only). Default 2 + headers: { + Authorization: Config.NEW_IMAGE_API, // Config.NEW_IMAGE_API + 'Content-Type': 'multipart/form-data', + }, + field: 'uploaded_media', + // Below are options only supported on Android + notification: { + enabled: true, + }, + useUtf8Charset: true, + }; - try { - let sign = await signImage(media, currentAccount, pinCode); + const uploadId = await Upload.startUpload(_options); - const _options: UploadOptions = { - url: `${Config.NEW_IMAGE_API}/hs/${sign}`, - path: Platform.select({ - ios: 'file://' + media.path, - android: media.path.replace('file://', '') - }), - method: 'POST', - type: 'multipart', - maxRetries: 2, // set retry count (Android only). Default 2 - headers: { - 'Authorization': Config.NEW_IMAGE_API, // Config.NEW_IMAGE_API - 'Content-Type': 'multipart/form-data', - }, - field: 'uploaded_media', - // Below are options only supported on Android - notification: { - enabled: true - }, - useUtf8Charset: true - } - - const uploadId = await Upload.startUpload(_options) - - console.log('Upload started', uploadId) - - Upload.addListener('progress', uploadId, (data) => { - console.log(`Progress: ${data.progress}%`, data) - }) - Upload.addListener('error', uploadId, (data) => { - console.log(`Error`, data) - throw data.error; - }) - Upload.addListener('cancelled', uploadId, (data) => { - console.log(`Cancelled!`, data) - throw new Error("Upload Cancelled") - }) - Upload.addListener('completed', uploadId, (data) => { - // data includes responseCode: number and responseBody: Object - console.log('Completed!', data) - const _respData = JSON.parse(data.responseBody); - resolve(_respData) - }) - } catch (err) { - console.warn("Meida Upload Failed", err); - reject(err) - } - }) - } + console.log('Upload started', uploadId); + Upload.addListener('progress', uploadId, (data) => { + console.log(`Progress: ${data.progress}%`, data); + }); + Upload.addListener('error', uploadId, (data) => { + console.log(`Error`, data); + throw data.error; + }); + Upload.addListener('cancelled', uploadId, (data) => { + console.log(`Cancelled!`, data); + throw new Error('Upload Cancelled'); + }); + Upload.addListener('completed', uploadId, (data) => { + // data includes responseCode: number and responseBody: Object + console.log('Completed!', data); + const _respData = JSON.parse(data.responseBody); + return _respData; + }); + } catch (err) { + console.warn('Meida Upload Failed', err); + bugsnapInstance.notify('Media upload failed', err); + throw err; + } + }; return useMutation( (vars) => { - return _uploadMedia(vars); }, { diff --git a/src/providers/queries/queryKeys.ts b/src/providers/queries/queryKeys.ts index b68a4af4a..4338ba5c2 100644 --- a/src/providers/queries/queryKeys.ts +++ b/src/providers/queries/queryKeys.ts @@ -13,7 +13,7 @@ const QUERIES = { }, MEDIA: { GET: 'QUERY_GET_UPLOADS', - GET_VIDEOS: 'QUERY_GET_VIDEO_UPLOADS' + GET_VIDEOS: 'QUERY_GET_VIDEO_UPLOADS', }, WALLET: { GET: 'QUERY_GET_ASSETS', diff --git a/src/providers/speak/constants.ts b/src/providers/speak/constants.ts index 9d4f8c209..03f77122a 100644 --- a/src/providers/speak/constants.ts +++ b/src/providers/speak/constants.ts @@ -1,11 +1,9 @@ +export const BASE_URL_SPEAK_STUDIO = 'https://studio.3speak.tv'; -export const BASE_URL_SPEAK_STUDIO = "https://studio.3speak.tv"; +export const BASE_URL_SPEAK_UPLOAD = 'https://uploads.3speak.tv/files'; -export const BASE_URL_SPEAK_UPLOAD = "https://uploads.3speak.tv/files"; +export const BASE_URL_SPEAK_WATCH = 'https://3speak.tv/watch'; -export const BASE_URL_SPEAK_WATCH = "https://3speak.tv/watch"; - - -export const PATH_MOBILE = "mobile"; -export const PATH_LOGIN = "login"; -export const PATH_API = "api"; +export const PATH_MOBILE = 'mobile'; +export const PATH_LOGIN = 'login'; +export const PATH_API = 'api'; diff --git a/src/providers/speak/converters.ts b/src/providers/speak/converters.ts index 208294f6c..b7c93de23 100644 --- a/src/providers/speak/converters.ts +++ b/src/providers/speak/converters.ts @@ -1,6 +1,5 @@ -import { MediaItem } from "../ecency/ecency.types" -import { BASE_URL_SPEAK_WATCH } from "./constants" - +import { MediaItem } from '../ecency/ecency.types'; +import { BASE_URL_SPEAK_WATCH } from './constants'; export const convertVideoUpload = (data) => { return { @@ -11,4 +10,4 @@ export const convertVideoUpload = (data) => { timestamp:0, speakData:data } as MediaItem -} \ No newline at end of file +} diff --git a/src/providers/speak/speak.ts b/src/providers/speak/speak.ts index 6285b9157..1c47a9c66 100644 --- a/src/providers/speak/speak.ts +++ b/src/providers/speak/speak.ts @@ -1,177 +1,172 @@ -import axios from "axios"; -import { getDigitPinCode } from "../hive/dhive"; -import { ThreeSpeakVideo } from "./speak.types"; -import { decryptKey } from "../../utils/crypto"; +import axios from 'axios'; import hs from 'hivesigner'; -import { convertVideoUpload } from "./converters"; -import { BASE_URL_SPEAK_STUDIO, PATH_API, PATH_LOGIN, PATH_MOBILE } from "./constants"; - -const tusEndPoint = "https://uploads.3speak.tv/files/"; +import { getDigitPinCode } from '../hive/dhive'; +import { ThreeSpeakVideo } from './speak.types'; +import { decryptKey } from '../../utils/crypto'; +import { convertVideoUpload } from './converters'; +import { BASE_URL_SPEAK_STUDIO, PATH_API, PATH_LOGIN, PATH_MOBILE } from './constants'; +const tusEndPoint = 'https://uploads.3speak.tv/files/'; const speakApi = axios.create({ - baseURL:`${BASE_URL_SPEAK_STUDIO}/${PATH_MOBILE}` + baseURL: `${BASE_URL_SPEAK_STUDIO}/${PATH_MOBILE}`, }); - - export const threespeakAuth = async (currentAccount: any, pinHash: string) => { - try { - let response = await speakApi.get( - `${PATH_LOGIN}?username=${currentAccount.username}&hivesigner=true`, - { - withCredentials: false, - headers: { - "Content-Type": "application/json" - } - } - ); - const memo_string = response.data.memo; - const memoDecoded = await getDecodedMemo(currentAccount.local, pinHash, memo_string); + try { + const response = await speakApi.get( + `${PATH_LOGIN}?username=${currentAccount.username}&hivesigner=true`, + { + withCredentials: false, + headers: { + 'Content-Type': 'application/json', + }, + }, + ); + const memo_string = response.data.memo; + const memoDecoded = await getDecodedMemo(currentAccount.local, pinHash, memo_string); - return memoDecoded.replace("#", ""); - - } catch (err) { - console.error(new Error("[3Speak auth] Failed to login")); - throw err; - } + return memoDecoded.replace('#', ''); + } catch (err) { + console.error(new Error('[3Speak auth] Failed to login')); + throw err; + } }; - - export const uploadVideoInfo = async ( - currentAccount: any, - pinHash: string, - oFilename: string, - fileSize: number, - videoUrl: string, - thumbnailUrl: string, - username: string, - duration: string + currentAccount: any, + pinHash: string, + oFilename: string, + fileSize: number, + videoUrl: string, + thumbnailUrl: string, + username: string, + duration: string, ) => { - const token = await threespeakAuth(currentAccount, pinHash); - try { - const { data } = await axios.post( - `${PATH_API}/upload_info?app=ecency`, - { - filename: videoUrl, - oFilename: oFilename, - size: fileSize, - duration, - thumbnail: thumbnailUrl, - isReel: false, - owner: username - }, - { - withCredentials: false, - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token}` - } - } - ); - return data; - } catch (e) { - console.error(e); - throw e; - } + const token = await threespeakAuth(currentAccount, pinHash); + try { + const { data } = await axios.post( + `${PATH_API}/upload_info?app=ecency`, + { + filename: videoUrl, + oFilename, + size: fileSize, + duration, + thumbnail: thumbnailUrl, + isReel: false, + owner: username, + }, + { + withCredentials: false, + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + }, + }, + ); + return data; + } catch (e) { + console.error(e); + throw e; + } }; export const getAllVideoStatuses = async (currentAccount: any, pinHash: string) => { - const token = await threespeakAuth(currentAccount, pinHash); - try { - let response = await speakApi.get(`${PATH_API}/my-videos`, { - withCredentials: false, - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token}` - } - }); + const token = await threespeakAuth(currentAccount, pinHash); + try { + const response = await speakApi.get(`${PATH_API}/my-videos`, { + withCredentials: false, + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + }, + }); - const mediaItems = response.data.map(convertVideoUpload); + const mediaItems = response.data.map(convertVideoUpload); - return mediaItems; - } catch (err) { - console.error(new Error("[3Speak video] Failed to get videos")); + return mediaItems; + } catch (err) { + console.error(new Error('[3Speak video] Failed to get videos')); - throw err; - } + throw err; + } }; export const updateSpeakVideoInfo = async ( - currentAccount: any, - pinHash: string, - postBody: string, - videoId: string, - title: string, - tags: string[], - isNsfwC: boolean + currentAccount: any, + pinHash: string, + postBody: string, + videoId: string, + title: string, + tags: string[], + isNsfwC: boolean, ) => { - const token = await threespeakAuth(currentAccount, pinHash); + const token = await threespeakAuth(currentAccount, pinHash); - const data = { - videoId: videoId, - title: title, - description: postBody, - isNsfwContent: isNsfwC, - tags_v2: tags - }; + const data = { + videoId, + title, + description: postBody, + isNsfwContent: isNsfwC, + tags_v2: tags, + }; - const headers = { - "Content-Type": "application/json", - Authorization: `Bearer ${token}` - }; + const headers = { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + }; - try { - await axios.post(`${PATH_API}/update_info`, data, { headers }); - } catch (e) { - console.error(e); - } + try { + await axios.post(`${PATH_API}/update_info`, data, { headers }); + } catch (e) { + console.error(e); + } }; export const markAsPublished = async (currentAccount: any, pinHash: string, videoId: string) => { - const token = await threespeakAuth(currentAccount, pinHash); - const data = { - videoId - }; + const token = await threespeakAuth(currentAccount, pinHash); + const data = { + videoId, + }; - const headers = { - "Content-Type": "application/json", - Authorization: `Bearer ${token}` - }; + const headers = { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + }; - axios - .post(`${PATH_API}/my-videos/iPublished`, data, { headers }) - .then((response) => { }) - .catch((error) => { - console.error("Error:", error); - }); + axios + .post(`${PATH_API}/my-videos/iPublished`, data, { headers }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error('Error:', error); + }); }; - export const uploadVideo = async (media, onUploadProgress) => { - try { - const file = { - uri: media.path, - type: media.mime, - name: media.filename || `img_${Math.random()}.mp4`, - size: media.size, - }; + try { + const file = { + uri: media.path, + type: media.mime, + name: media.filename || `img_${Math.random()}.mp4`, + size: media.size, + }; - const fData = new FormData(); - fData.append('file', file); + const fData = new FormData(); + fData.append('file', file); - const res = await axios.post(tusEndPoint, fData, { - onUploadProgress - }); - if (!res || !res.data) { - throw new Error('Returning response missing media data'); - } - return res.data; - } catch (error) { - console.warn('Image upload failed', error); - throw error; + const res = await axios.post(tusEndPoint, fData, { + onUploadProgress, + }); + if (!res || !res.data) { + throw new Error('Returning response missing media data'); } + return res.data; + } catch (error) { + console.warn('Image upload failed', error); + throw error; + } }; // export const uploadFile = async ( @@ -220,26 +215,23 @@ export const uploadVideo = async (media, onUploadProgress) => { // }); // }; - const getDecodedMemo = async (local, pinHash, encryptedMemo) => { - try { - const digitPinCode = getDigitPinCode(pinHash) - const token = decryptKey(local.accessToken, digitPinCode); + try { + const digitPinCode = getDigitPinCode(pinHash); + const token = decryptKey(local.accessToken, digitPinCode); - const client = new hs.Client({ - accessToken: token, - }) + const client = new hs.Client({ + accessToken: token, + }); - const { memoDecoded } = await client.decode(encryptedMemo); + const { memoDecoded } = await client.decode(encryptedMemo); - if (!memoDecoded) { - throw new Error("Decode failed") - } - - return memoDecoded; - - } catch (err) { - console.warn("Failed to decode memo key", err) + if (!memoDecoded) { + throw new Error('Decode failed'); } -} \ No newline at end of file + return memoDecoded; + } catch (err) { + console.warn('Failed to decode memo key', err); + } +}; diff --git a/src/providers/speak/speak.types.ts b/src/providers/speak/speak.types.ts index 1777203c6..b8eab1eaa 100644 --- a/src/providers/speak/speak.types.ts +++ b/src/providers/speak/speak.types.ts @@ -1,52 +1,52 @@ export interface ThreeSpeakVideo { - app: string; - beneficiaries: string; // e.g. "[{\"account\":\"actifit-he\",\"weight\":100,\"src\":\"ENCODER_PAY\"}]" - category: string; - community: unknown | null; - created: string; // e.g. "2023-06-21T12:02:10.421Z" - declineRewards: boolean; - description: string; - donations: boolean; - duration: number; - encoding: Record; - encodingProgress: number; - encoding_price_steem: string; - filename: string; - firstUpload: boolean; - fromMobile: boolean; - height: unknown; - hive: string; - indexed: boolean; - is3CJContent: boolean; - isNsfwContent: boolean; - isReel: boolean; - isVOD: boolean; - job_id: string; - language: string; - local_filename: string; - lowRc: boolean; - needsBlockchainUpdate: boolean; - originalFilename: string; - owner: string; - paid: boolean; - permlink: string; - postToHiveBlog: boolean; - publish_type: string; - reducedUpvote: boolean; - rewardPowerup: boolean; - size: number; - status: string; - tags_v2: unknown[]; - thumbUrl: string; - thumbnail: string; - title: string; - updateSteem: boolean; - upload_type: string; - upvoteEligible: boolean; - video_v2: string; - views: number; - votePercent: number; - width: unknown; - __v: number; - _id: string; -} \ No newline at end of file + app: string; + beneficiaries: string; // e.g. "[{\"account\":\"actifit-he\",\"weight\":100,\"src\":\"ENCODER_PAY\"}]" + category: string; + community: unknown | null; + created: string; // e.g. "2023-06-21T12:02:10.421Z" + declineRewards: boolean; + description: string; + donations: boolean; + duration: number; + encoding: Record; + encodingProgress: number; + encoding_price_steem: string; + filename: string; + firstUpload: boolean; + fromMobile: boolean; + height: unknown; + hive: string; + indexed: boolean; + is3CJContent: boolean; + isNsfwContent: boolean; + isReel: boolean; + isVOD: boolean; + job_id: string; + language: string; + local_filename: string; + lowRc: boolean; + needsBlockchainUpdate: boolean; + originalFilename: string; + owner: string; + paid: boolean; + permlink: string; + postToHiveBlog: boolean; + publish_type: string; + reducedUpvote: boolean; + rewardPowerup: boolean; + size: number; + status: string; + tags_v2: unknown[]; + thumbUrl: string; + thumbnail: string; + title: string; + updateSteem: boolean; + upload_type: string; + upvoteEligible: boolean; + video_v2: string; + views: number; + votePercent: number; + width: unknown; + __v: number; + _id: string; +} diff --git a/src/screens/editor/children/styles.ts b/src/screens/editor/children/styles.ts index 6b97e36ff..f18ec4980 100644 --- a/src/screens/editor/children/styles.ts +++ b/src/screens/editor/children/styles.ts @@ -1,5 +1,4 @@ import EStyleSheet from 'react-native-extended-stylesheet'; -import { getBottomSpace } from 'react-native-iphone-x-helper'; export default EStyleSheet.create({ sheetContent: { diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 912499e95..12e7521e2 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -10,6 +10,7 @@ import { isArray } from 'lodash'; import { Buffer } from 'buffer'; import { useQueryClient } from '@tanstack/react-query'; import { gestureHandlerRootHOC } from 'react-native-gesture-handler'; +import { postBodySummary } from '@ecency/render-helper'; import { addDraft, updateDraft, getDrafts, addSchedule } from '../../../providers/ecency/ecency'; import { toastNotification, setRcOffer } from '../../../redux/actions/uiAction'; import { @@ -50,7 +51,6 @@ import { useUserActivityMutation } from '../../../providers/queries/pointQueries import { PointActivityIds } from '../../../providers/ecency/ecency.types'; import { usePostsCachePrimer } from '../../../providers/queries/postQueries/postQueries'; import { PostTypes } from '../../../constants/postTypes'; -import { postBodySummary } from '@ecency/render-helper'; /* * Props Name Description Value @@ -456,7 +456,7 @@ class EditorContainer extends Component { tags: draftField.tags, beneficiaries, rewardType, - description: postDescription ? postDescription : postBodySummaryContent, + description: postDescription || postBodySummaryContent, }); const jsonMeta = makeJsonMetadata(meta, draftField.tags); From 51b45af76e60e3881b06615cd6bec11d7719c525 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Tue, 14 Nov 2023 17:41:40 +0500 Subject: [PATCH 052/111] cross compatible drafts with speak video items --- .../editor/container/editorContainer.tsx | 15 ++++++ src/utils/editor.ts | 51 +++++++++++-------- 2 files changed, 46 insertions(+), 20 deletions(-) diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 12e7521e2..8f7f7d35e 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -33,6 +33,7 @@ import { extractMetadata, makeJsonMetadataForUpdate, createPatch, + extract3SpeakIds, } from '../../../utils/editor'; // import { generateSignature } from '../../../utils/image'; @@ -452,11 +453,25 @@ class EditorContainer extends Component { thumbUrl, fetchRatios: false, }); + + // inject video meta for draft + const speakIds = extract3SpeakIds({ body: draftField.body }); + const videos: any = {}; + const videosCache: any = queryClient.getQueryData([QUERIES.MEDIA.GET_VIDEOS]); + + speakIds.forEach((_id) => { + const videoItem = videosCache.find((item) => item._id === _id); + if (videoItem?.speakData) { + videos[_id] = videoItem.speakData; + } + }); + const meta = Object.assign({}, _extractedMeta, { tags: draftField.tags, beneficiaries, rewardType, description: postDescription || postBodySummaryContent, + videos: Object.keys(videos).length > 0 && videos, }); const jsonMeta = makeJsonMetadata(meta, draftField.tags); diff --git a/src/utils/editor.ts b/src/utils/editor.ts index ad8703d49..a5931a38e 100644 --- a/src/utils/editor.ts +++ b/src/utils/editor.ts @@ -186,6 +186,20 @@ export const extractImageUrls = ({ body, urls }: { body?: string; urls?: string[ return imgUrls; }; +export const extract3SpeakIds = ({ body }) => { + if (!body) { + return []; + } + + const regex = /\[3speak]\((.*?)\)/g; + const matches = [...body.matchAll(regex)]; + + const ids = matches.map((match) => match[1]); + console.log(ids); + + return ids; +}; + export const extractFilenameFromPath = ({ path, mimeType, @@ -217,22 +231,22 @@ export const extractMetadata = async ({ thumbUrl, fetchRatios, postType, - threeSpeakMeta + threeSpeakMeta, }: { body: string; thumbUrl?: string; fetchRatios?: boolean; postType?: PostTypes; threeSpeakMeta?: { - title:string, - description:string, - rawData:ThreeSpeakVideo - } + title: string; + description: string; + rawData: ThreeSpeakVideo; + }; }) => { // NOTE: keepting regex to extract usernames as reference for later usage if any // const userReg = /(^|\s)(@[a-z][-.a-z\d]+[a-z\d])/gim; - const out:any = {}; + const out: any = {}; const mUrls = extractUrls(body); const matchedImages = extractImageUrls({ urls: mUrls }); @@ -268,7 +282,7 @@ export const extractMetadata = async ({ const videoMetadata = threeSpeakMeta.rawData; out.video = { info: { - platform: "3speak", + platform: '3speak', title: threeSpeakMeta.title || videoMetadata.title, author: videoMetadata.owner, permlink: videoMetadata.permlink, @@ -282,28 +296,25 @@ export const extractMetadata = async ({ video_v2: videoMetadata.video_v2, sourceMap: [ { - type: "video", + type: 'video', url: videoMetadata.video_v2, - format: "m3u8" + format: 'm3u8', }, { - type: "thumbnail", - url: videoMetadata.thumbUrl - } - ] + type: 'thumbnail', + url: videoMetadata.thumbUrl, + }, + ], }, content: { description: threeSpeakMeta.description || videoMetadata.description, - tags: videoMetadata.tags_v2 - } + tags: videoMetadata.tags_v2, + }, }; } - - - //setting post type, primary usecase for separating waves from other posts - out.type = postType || PostTypes.POST - + // setting post type, primary usecase for separating waves from other posts + out.type = postType || PostTypes.POST; return out; }; From 946b9c18670b16c08b7e56ac08d237f87debd085 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Tue, 14 Nov 2023 18:16:59 +0500 Subject: [PATCH 053/111] added todo tags --- src/components/markdownEditor/children/editorToolbar.tsx | 1 + src/providers/queries/editorQueries.ts | 2 ++ src/screens/editor/container/editorContainer.tsx | 8 ++++++++ 3 files changed, 11 insertions(+) diff --git a/src/components/markdownEditor/children/editorToolbar.tsx b/src/components/markdownEditor/children/editorToolbar.tsx index b2630fbd2..126202a3d 100644 --- a/src/components/markdownEditor/children/editorToolbar.tsx +++ b/src/components/markdownEditor/children/editorToolbar.tsx @@ -270,6 +270,7 @@ export const EditorToolbar = ({ iconType="FontAwesome" name="image" /> + {/* TODO: do not show video insert for replies and waves for now */} { const _fetchVideoUploads = async () => getAllVideoStatuses(currentAccount, pinHash); + // TOOD: filter cache data for post edits to only show already published videos + return useQuery([QUERIES.MEDIA.GET_VIDEOS], _fetchVideoUploads, { initialData: [], onError: () => { diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 8f7f7d35e..18d90df6f 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -612,10 +612,16 @@ class EditorContainer extends Component { isPostSending: true, }); + // TOOD: build speak body + + // only require video meta for unpublished video, it will always be one const meta = await extractMetadata({ body: fields.body, thumbUrl, fetchRatios: true }); const _tags = fields.tags.filter((tag) => tag && tag !== ' '); const jsonMeta = makeJsonMetadata(meta, _tags); + + // TODO: build speak video body + // TODO: check if permlink is available github: #314 https://github.com/ecency/ecency-mobile/pull/314 let permlink = generatePermlink(fields.title || ''); @@ -843,6 +849,8 @@ class EditorContainer extends Component { jsonMeta = makeJsonMetadata(meta, tags); } + // TODO: build speak video body + await postContent( currentAccount, pinCode, From b7238dcd6e3e36ba25faec93ed7afdef1856161a Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Tue, 14 Nov 2023 18:18:56 +0500 Subject: [PATCH 054/111] lint --- .../children/formats/applyMediaLink.ts | 1 - .../container/uploadsGalleryModal.tsx | 4 ++-- src/index.tsx | 2 +- src/navigation/stackNavigator.tsx | 2 +- src/providers/ecency/ecency.types.ts | 2 +- src/providers/speak/converters.ts | 18 +++++++++--------- .../editor/container/editorContainer.tsx | 4 ++++ 7 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/components/markdownEditor/children/formats/applyMediaLink.ts b/src/components/markdownEditor/children/formats/applyMediaLink.ts index 37bff963b..2ca45fb8a 100644 --- a/src/components/markdownEditor/children/formats/applyMediaLink.ts +++ b/src/components/markdownEditor/children/formats/applyMediaLink.ts @@ -25,7 +25,6 @@ export default async ({ text, selection, setTextAndSelection, items }: Args) => const imagePrefix = '!'; - const placeholderPrefix = 'Uploading... '; let newText = text; diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 6de72f160..863d45481 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -385,9 +385,9 @@ export const UploadsGalleryModal = forwardRef( map.forEach((value, index) => { console.log(index); - const item:MediaItem = mediaUploadsQuery.data[index]; + const item: MediaItem = mediaUploadsQuery.data[index]; data.push({ - url: mode === Modes.MODE_VIDEO ? (item.speakData?._id || '') : item.url, + url: mode === Modes.MODE_VIDEO ? item.speakData?._id || '' : item.url, text: mode === Modes.MODE_VIDEO ? `3speak` : '', status: MediaInsertStatus.READY, mode, diff --git a/src/index.tsx b/src/index.tsx index d0b62ab38..e8195ee06 100755 --- a/src/index.tsx +++ b/src/index.tsx @@ -17,7 +17,7 @@ const queryClientProviderProps = initQueryClient(); if (__DEV__) { import('react-query-native-devtools').then(({ addPlugin }) => { - addPlugin({ queryClient:queryClientProviderProps.client }); + addPlugin({ queryClient: queryClientProviderProps.client }); }); } diff --git a/src/navigation/stackNavigator.tsx b/src/navigation/stackNavigator.tsx index 5d32c2530..bbca11c03 100644 --- a/src/navigation/stackNavigator.tsx +++ b/src/navigation/stackNavigator.tsx @@ -46,7 +46,7 @@ const MainStackNavigator = () => { // TODO: remove initialRoute before PR return ( diff --git a/src/providers/ecency/ecency.types.ts b/src/providers/ecency/ecency.types.ts index fe4097ef1..43e068d8f 100644 --- a/src/providers/ecency/ecency.types.ts +++ b/src/providers/ecency/ecency.types.ts @@ -14,7 +14,7 @@ export interface MediaItem { thumbUrl: string; created: string; timestamp: number; - speakData?:ThreeSpeakVideo + speakData?: ThreeSpeakVideo; } export interface Snippet { diff --git a/src/providers/speak/converters.ts b/src/providers/speak/converters.ts index b7c93de23..dc4436c51 100644 --- a/src/providers/speak/converters.ts +++ b/src/providers/speak/converters.ts @@ -2,12 +2,12 @@ import { MediaItem } from '../ecency/ecency.types'; import { BASE_URL_SPEAK_WATCH } from './constants'; export const convertVideoUpload = (data) => { - return { - _id:data._id, - url:`${BASE_URL_SPEAK_WATCH}?v=${data.owner}/${data.permlink}`, - thumbUrl:data.thumbUrl, - created:data.created, - timestamp:0, - speakData:data - } as MediaItem -} + return { + _id: data._id, + url: `${BASE_URL_SPEAK_WATCH}?v=${data.owner}/${data.permlink}`, + thumbUrl: data.thumbUrl, + created: data.created, + timestamp: 0, + speakData: data, + } as MediaItem; +}; diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 18d90df6f..c157b5c2a 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -672,6 +672,7 @@ class EditorContainer extends Component { ) .then((response) => { console.log(response); + // track user activity for points userActivityMutation.mutate({ pointsTy: PointActivityIds.POST, @@ -694,6 +695,9 @@ class EditorContainer extends Component { }); } + + //TODO: mark unpublished video as published on 3speak if that is the case + // post publish updates dispatch(deleteDraftCacheEntry(DEFAULT_USER_DRAFT_ID + currentAccount.name)); From 6116ab7a06511ec39d7bb96fcafd4b957cfb71da Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Wed, 15 Nov 2023 13:15:44 +0500 Subject: [PATCH 055/111] refractored editor queries --- .../snippetEditorModal/snippetEditorModal.tsx | 4 +-- src/components/snippetsModal/snippetItem.tsx | 4 +-- .../snippetsModal/snippetsModal.tsx | 4 +-- .../children/uploadsGalleryContent.tsx | 4 +-- .../container/uploadsGalleryModal.tsx | 11 +++---- .../{ => editorQueries}/editorQueries.ts | 31 +++++-------------- src/providers/queries/editorQueries/index.ts | 4 +++ src/utils/editor.ts | 17 +++++----- 8 files changed, 31 insertions(+), 48 deletions(-) rename src/providers/queries/{ => editorQueries}/editorQueries.ts (87%) create mode 100644 src/providers/queries/editorQueries/index.ts diff --git a/src/components/snippetEditorModal/snippetEditorModal.tsx b/src/components/snippetEditorModal/snippetEditorModal.tsx index e7356e5db..4838d149b 100644 --- a/src/components/snippetEditorModal/snippetEditorModal.tsx +++ b/src/components/snippetEditorModal/snippetEditorModal.tsx @@ -4,7 +4,7 @@ import { Alert, KeyboardAvoidingView, Platform, View } from 'react-native'; import { useSelector } from 'react-redux'; import { TextInput } from '..'; import { Snippet } from '../../models'; -import { useSnippetsMutation } from '../../providers/queries'; +import { editorQueries } from '../../providers/queries'; import { TextButton } from '../buttons'; import Modal from '../modal'; import styles from './snippetEditorModalStyles'; @@ -19,7 +19,7 @@ const SnippetEditorModal = ({}, ref) => { const titleInputRef = useRef(null); const bodyInputRef = useRef(null); - const snippetsMutation = useSnippetsMutation(); + const snippetsMutation = editorQueries.useSnippetsMutation(); const [title, setTitle] = useState(''); const [body, setBody] = useState(''); diff --git a/src/components/snippetsModal/snippetItem.tsx b/src/components/snippetsModal/snippetItem.tsx index 46a248efe..90e41dba9 100644 --- a/src/components/snippetsModal/snippetItem.tsx +++ b/src/components/snippetsModal/snippetItem.tsx @@ -1,7 +1,7 @@ import * as React from 'react'; import { useIntl } from 'react-intl'; import { Alert, Text, View } from 'react-native'; -import { useSnippetDeleteMutation } from '../../providers/queries'; +import { editorQueries } from '../../providers/queries'; import IconButton from '../iconButton'; import styles from './snippetsModalStyles'; @@ -15,7 +15,7 @@ interface SnippetItemProps { const SnippetItem = ({ id, title, body, index, onEditPress }: SnippetItemProps) => { const intl = useIntl(); - const snippetsDeleteMutation = useSnippetDeleteMutation(); + const snippetsDeleteMutation = editorQueries.useSnippetDeleteMutation(); const _onRemovePress = () => { // asks for remvoe confirmation and run remove routing upon confirming diff --git a/src/components/snippetsModal/snippetsModal.tsx b/src/components/snippetsModal/snippetsModal.tsx index c8ca05c7c..23edbc4a6 100644 --- a/src/components/snippetsModal/snippetsModal.tsx +++ b/src/components/snippetsModal/snippetsModal.tsx @@ -10,7 +10,7 @@ import SnippetEditorModal, { import SnippetItem from './snippetItem'; import { Snippet } from '../../models'; import { useAppSelector } from '../../hooks'; -import { useSnippetsQuery } from '../../providers/queries'; +import { editorQueries } from '../../providers/queries'; interface SnippetsModalProps { handleOnSelect: (snippetText: string) => void; @@ -22,7 +22,7 @@ const SnippetsModal = ({ handleOnSelect }: SnippetsModalProps) => { const isLoggedIn = useAppSelector((state) => state.application.isLoggedIn); - const snippetsQuery = useSnippetsQuery(); + const snippetsQuery = editorQueries.useSnippetsQuery(); // render list item for snippet and handle actions; const _renderItem = ({ item, index }: { item: Snippet; index: number }) => { diff --git a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx index 38ed3a9b3..5f9ade7ea 100644 --- a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx +++ b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx @@ -26,7 +26,7 @@ import styles, { EXPANDED_HEIGHT, MAX_HORIZONTAL_THUMBS, } from './uploadsGalleryModalStyles'; -import { useMediaDeleteMutation } from '../../../providers/queries'; +import { editorQueries } from '../../../providers/queries'; import { MediaItem } from '../../../providers/ecency/ecency.types'; type Props = { @@ -48,7 +48,7 @@ const UploadsGalleryContent = ({ }: Props) => { const intl = useIntl(); - const deleteMediaMutation = useMediaDeleteMutation(); + const deleteMediaMutation = editorQueries.useMediaDeleteMutation(); const [deleteIds, setDeleteIds] = useState([]); const [isDeleteMode, setIsDeleteMode] = useState(false); diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 863d45481..0dba603db 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -18,9 +18,8 @@ import { useAppDispatch, useAppSelector } from '../../../hooks'; import { delay, extractFilenameFromPath } from '../../../utils/editor'; import showLoginAlert from '../../../utils/showLoginAlert'; import { - useMediaQuery, - useMediaUploadMutation, - useVideoUploadsQuery, + editorQueries, + speakQueries, } from '../../../providers/queries'; import { showActionModal } from '../../../redux/actions/uiAction'; import { MediaItem } from '../../../providers/ecency/ecency.types'; @@ -76,10 +75,10 @@ export const UploadsGalleryModal = forwardRef( const intl = useIntl(); const dispatch = useAppDispatch(); - const imageUploadsQuery = useMediaQuery(); - const videoUploadsQuery = useVideoUploadsQuery(); + const imageUploadsQuery = editorQueries.useMediaQuery(); + const videoUploadsQuery = speakQueries.useVideoUploadsQuery(); - const mediaUploadMutation = useMediaUploadMutation(); + const mediaUploadMutation = editorQueries.useMediaUploadMutation(); const pendingInserts = useRef([]); diff --git a/src/providers/queries/editorQueries.ts b/src/providers/queries/editorQueries/editorQueries.ts similarity index 87% rename from src/providers/queries/editorQueries.ts rename to src/providers/queries/editorQueries/editorQueries.ts index 6ed468456..377bc41a4 100644 --- a/src/providers/queries/editorQueries.ts +++ b/src/providers/queries/editorQueries/editorQueries.ts @@ -4,8 +4,8 @@ import { Image } from 'react-native-image-crop-picker'; import Upload, { UploadOptions } from 'react-native-background-upload'; import Config from 'react-native-config'; import { Platform } from 'react-native'; -import { useAppDispatch, useAppSelector } from '../../hooks'; -import { toastNotification } from '../../redux/actions/uiAction'; +import { useAppDispatch, useAppSelector } from '../../../hooks'; +import { toastNotification } from '../../../redux/actions/uiAction'; import { addFragment, addImage, @@ -14,13 +14,11 @@ import { getFragments, getImages, updateFragment, -} from '../ecency/ecency'; -import { MediaItem, Snippet } from '../ecency/ecency.types'; -import { signImage } from '../hive/dhive'; -import QUERIES from './queryKeys'; -import { getAllVideoStatuses } from '../speak/speak'; -import { ThreeSpeakVideo } from '../speak/speak.types'; -import bugsnapInstance from '../../config/bugsnag'; +} from '../../ecency/ecency'; +import { MediaItem, Snippet } from '../../ecency/ecency.types'; +import { signImage } from '../../hive/dhive'; +import QUERIES from '../queryKeys'; +import bugsnapInstance from '../../../config/bugsnag'; interface SnippetMutationVars { id: string | null; @@ -80,24 +78,9 @@ export const useAddToUploadsMutation = () => { }); }; -export const useVideoUploadsQuery = () => { - const intl = useIntl(); - const dispatch = useAppDispatch(); - const currentAccount = useAppSelector((state) => state.account.currentAccount); - const pinHash = useAppSelector((state) => state.application.pin); - const _fetchVideoUploads = async () => getAllVideoStatuses(currentAccount, pinHash); - // TOOD: filter cache data for post edits to only show already published videos - - return useQuery([QUERIES.MEDIA.GET_VIDEOS], _fetchVideoUploads, { - initialData: [], - onError: () => { - dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); - }, - }); -}; export const useMediaUploadMutation = () => { const intl = useIntl(); diff --git a/src/providers/queries/editorQueries/index.ts b/src/providers/queries/editorQueries/index.ts new file mode 100644 index 000000000..86090d18e --- /dev/null +++ b/src/providers/queries/editorQueries/index.ts @@ -0,0 +1,4 @@ +import * as editorQueries from './editorQueries'; +import * as speakQueries from './speakQueries'; + +export { editorQueries, speakQueries }; diff --git a/src/utils/editor.ts b/src/utils/editor.ts index a5931a38e..ce194b4cc 100644 --- a/src/utils/editor.ts +++ b/src/utils/editor.ts @@ -231,17 +231,13 @@ export const extractMetadata = async ({ thumbUrl, fetchRatios, postType, - threeSpeakMeta, + videoPublishMeta, }: { body: string; thumbUrl?: string; fetchRatios?: boolean; postType?: PostTypes; - threeSpeakMeta?: { - title: string; - description: string; - rawData: ThreeSpeakVideo; - }; + videoPublishMeta?: ThreeSpeakVideo; }) => { // NOTE: keepting regex to extract usernames as reference for later usage if any // const userReg = /(^|\s)(@[a-z][-.a-z\d]+[a-z\d])/gim; @@ -278,12 +274,13 @@ export const extractMetadata = async ({ ); } - if (threeSpeakMeta) { - const videoMetadata = threeSpeakMeta.rawData; + //insert three speak meta + if (videoPublishMeta) { + const videoMetadata = videoPublishMeta.rawData; out.video = { info: { platform: '3speak', - title: threeSpeakMeta.title || videoMetadata.title, + title: videoMetadata.title, author: videoMetadata.owner, permlink: videoMetadata.permlink, duration: videoMetadata.duration, @@ -307,7 +304,7 @@ export const extractMetadata = async ({ ], }, content: { - description: threeSpeakMeta.description || videoMetadata.description, + description: videoMetadata.description, tags: videoMetadata.tags_v2, }, }; From 6505624a5518392146167a80f8fabde14a0cd1b4 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Wed, 15 Nov 2023 13:33:47 +0500 Subject: [PATCH 056/111] building speak urls before publishing content --- .../queries/editorQueries/speakQueries.ts | 67 +++++++++++++++++++ .../editor/container/editorContainer.tsx | 30 +++++++-- 2 files changed, 90 insertions(+), 7 deletions(-) create mode 100644 src/providers/queries/editorQueries/speakQueries.ts diff --git a/src/providers/queries/editorQueries/speakQueries.ts b/src/providers/queries/editorQueries/speakQueries.ts new file mode 100644 index 000000000..04f2962bb --- /dev/null +++ b/src/providers/queries/editorQueries/speakQueries.ts @@ -0,0 +1,67 @@ +import { useQuery } from "@tanstack/react-query"; +import { useIntl } from "react-intl"; +import { useAppDispatch, useAppSelector } from "../../../hooks"; +import { toastNotification } from "../../../redux/actions/uiAction"; +import { MediaItem } from "../../ecency/ecency.types"; +import { getAllVideoStatuses } from "../../speak/speak"; +import QUERIES from "../queryKeys"; +import { extract3SpeakIds } from "../../../utils/editor"; +import { useRef } from "react"; +import { ThreeSpeakVideo } from "../../speak/speak.types"; + +/** + * fetches and caches speak video uploads + * @returns query instance with data as array of videos as MediaItem[] + */ +export const useVideoUploadsQuery = () => { + const intl = useIntl(); + const dispatch = useAppDispatch(); + + const currentAccount = useAppSelector((state) => state.account.currentAccount); + const pinHash = useAppSelector((state) => state.application.pin); + + const _fetchVideoUploads = async () => getAllVideoStatuses(currentAccount, pinHash); + + // TOOD: filter cache data for post edits to only show already published videos + + return useQuery([QUERIES.MEDIA.GET_VIDEOS], _fetchVideoUploads, { + initialData: [], + onError: () => { + dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); + }, + }); + }; + + +export const useSpeakContentBuilder = () => { + + const videoUploads = useVideoUploadsQuery(); + const videoPublishMetaRef = useRef(null); + + const build = (body:string) => { + let _newBody = body; + const _ids = extract3SpeakIds({body}); + + _ids.forEach((id) => { + const mediaItem:MediaItem|undefined = videoUploads.data.find((item) => item._id === id); + if(mediaItem){ + + //TODO: check if video is unpublished, set unpublish video meta + + + //replace 3speak with actual data + const _toReplaceStr = `[3speak](${id})`; + const _replacement = `
[![](${mediaItem.thumbUrl})](${mediaItem.url})
` + _newBody = _newBody.replace(_toReplaceStr, _replacement) + + } + }) + + return _newBody; + } + + return { + build, + videoPublishMeta:videoPublishMetaRef.current + } +} \ No newline at end of file diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index c157b5c2a..903b22969 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -52,6 +52,7 @@ import { useUserActivityMutation } from '../../../providers/queries/pointQueries import { PointActivityIds } from '../../../providers/ecency/ecency.types'; import { usePostsCachePrimer } from '../../../providers/queries/postQueries/postQueries'; import { PostTypes } from '../../../constants/postTypes'; +import { speakQueries } from '../../../providers/queries'; /* * Props Name Description Value @@ -597,6 +598,7 @@ class EditorContainer extends Component { navigation, pinCode, userActivityMutation, + speakContentBuilder, // isDefaultFooter, } = this.props; const { rewardType, isPostSending, thumbUrl, draftId, shouldReblog } = this.state; @@ -612,16 +614,21 @@ class EditorContainer extends Component { isPostSending: true, }); - // TOOD: build speak body + + // build speak video body + fields.body = speakContentBuilder.build(fields.body); // only require video meta for unpublished video, it will always be one - const meta = await extractMetadata({ body: fields.body, thumbUrl, fetchRatios: true }); + const meta = await extractMetadata({ + body: fields.body, + thumbUrl, + fetchRatios: true, + videoPublishMeta: speakContentBuilder.videoPublishMeta + }); const _tags = fields.tags.filter((tag) => tag && tag !== ' '); const jsonMeta = makeJsonMetadata(meta, _tags); - // TODO: build speak video body - // TODO: check if permlink is available github: #314 https://github.com/ecency/ecency-mobile/pull/314 let permlink = generatePermlink(fields.title || ''); @@ -736,7 +743,7 @@ class EditorContainer extends Component { }; _submitReply = async (fields) => { - const { currentAccount, pinCode, dispatch, userActivityMutation, draftsCollection } = + const { currentAccount, pinCode, dispatch, userActivityMutation, draftsCollection, speakContentBuilder } = this.props; const { isPostSending } = this.state; @@ -751,6 +758,8 @@ class EditorContainer extends Component { const { post } = this.state; + fields.body = speakContentBuilder.build(fields.body); + const _prefix = `re-${post.author.replace(/\./g, '')}`; const permlink = generateUniquePermlink(_prefix); @@ -759,6 +768,8 @@ class EditorContainer extends Component { const parentTags = post.json_metadata.tags; const draftId = `${currentAccount.name}/${parentAuthor}/${parentPermlink}`; // different draftId for each user acount + + const meta = await extractMetadata({ body: fields.body, fetchRatios: true, @@ -815,7 +826,7 @@ class EditorContainer extends Component { }; _submitEdit = async (fields) => { - const { currentAccount, pinCode, dispatch, postCachePrimer } = this.props; + const { currentAccount, pinCode, dispatch, postCachePrimer, speakContentBuilder } = this.props; const { post, isEdit, isPostSending, thumbUrl, isReply } = this.state; if (isPostSending) { @@ -826,6 +837,11 @@ class EditorContainer extends Component { this.setState({ isPostSending: true, }); + + //build speak video body + fields.body = speakContentBuilder.build(fields.body); + + const { tags, body, title } = fields; const { markdownBody: oldBody, @@ -853,7 +869,6 @@ class EditorContainer extends Component { jsonMeta = makeJsonMetadata(meta, tags); } - // TODO: build speak video body await postContent( currentAccount, @@ -1243,6 +1258,7 @@ const mapStateToProps = (state) => ({ const mapQueriesToProps = () => ({ queryClient: useQueryClient(), + speakContentBuilder: speakQueries.useSpeakContentBuilder(), userActivityMutation: useUserActivityMutation(), postCachePrimer: usePostsCachePrimer(), }); From 09be4dec9a7c19dd1a2713e7dab5c6f6137264c0 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Wed, 15 Nov 2023 15:52:16 +0500 Subject: [PATCH 057/111] adding unpublished meta to new post submission --- src/providers/queries/editorQueries/speakQueries.ts | 8 +++++--- src/providers/speak/speak.types.ts | 10 +++++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/providers/queries/editorQueries/speakQueries.ts b/src/providers/queries/editorQueries/speakQueries.ts index 04f2962bb..efe0b163e 100644 --- a/src/providers/queries/editorQueries/speakQueries.ts +++ b/src/providers/queries/editorQueries/speakQueries.ts @@ -7,7 +7,7 @@ import { getAllVideoStatuses } from "../../speak/speak"; import QUERIES from "../queryKeys"; import { extract3SpeakIds } from "../../../utils/editor"; import { useRef } from "react"; -import { ThreeSpeakVideo } from "../../speak/speak.types"; +import { ThreeSpeakStatus, ThreeSpeakVideo } from "../../speak/speak.types"; /** * fetches and caches speak video uploads @@ -46,8 +46,10 @@ export const useSpeakContentBuilder = () => { const mediaItem:MediaItem|undefined = videoUploads.data.find((item) => item._id === id); if(mediaItem){ - //TODO: check if video is unpublished, set unpublish video meta - + //check if video is unpublished, set unpublish video meta + if(!videoPublishMetaRef.current && mediaItem.speakData?.status === ThreeSpeakStatus.READY){ + videoPublishMetaRef.current = mediaItem.speakData; + } //replace 3speak with actual data const _toReplaceStr = `[3speak](${id})`; diff --git a/src/providers/speak/speak.types.ts b/src/providers/speak/speak.types.ts index b8eab1eaa..faca0cab4 100644 --- a/src/providers/speak/speak.types.ts +++ b/src/providers/speak/speak.types.ts @@ -1,3 +1,11 @@ +export enum ThreeSpeakStatus { + PUBLISHED = 'published', + READY = 'publish_manual', + DELETED = 'deleted', + ENCODING = 'encoding_ipfs' +} + + export interface ThreeSpeakVideo { app: string; beneficiaries: string; // e.g. "[{\"account\":\"actifit-he\",\"weight\":100,\"src\":\"ENCODER_PAY\"}]" @@ -35,7 +43,7 @@ export interface ThreeSpeakVideo { reducedUpvote: boolean; rewardPowerup: boolean; size: number; - status: string; + status: ThreeSpeakStatus; tags_v2: unknown[]; thumbUrl: string; thumbnail: string; From ccd7d9988418d7cca0dde8a3b8b79d4d5bd5bc5b Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Wed, 15 Nov 2023 17:20:29 +0500 Subject: [PATCH 058/111] rendering video status --- .../children/mediaPreviewItem.tsx | 84 ++++++++++++++ .../children/uploadsGalleryContent.tsx | 52 ++------- .../children/uploadsGalleryModalStyles.ts | 19 +++ src/config/locales/en-US.json | 6 +- .../queries/editorQueries/speakQueries.ts | 108 ++++++++++++++---- .../editor/container/editorContainer.tsx | 6 +- 6 files changed, 210 insertions(+), 65 deletions(-) create mode 100644 src/components/uploadsGalleryModal/children/mediaPreviewItem.tsx diff --git a/src/components/uploadsGalleryModal/children/mediaPreviewItem.tsx b/src/components/uploadsGalleryModal/children/mediaPreviewItem.tsx new file mode 100644 index 000000000..072cecf01 --- /dev/null +++ b/src/components/uploadsGalleryModal/children/mediaPreviewItem.tsx @@ -0,0 +1,84 @@ + +import React from 'react'; +import { proxifyImageSrc } from '@ecency/render-helper'; +import { + Platform, + Text, + TouchableOpacity, + View +} from 'react-native'; +import EStyleSheet from 'react-native-extended-stylesheet'; +import FastImage from 'react-native-fast-image'; +import { + default as AnimatedView, + ZoomIn +} from 'react-native-reanimated'; +import { Icon } from '../..'; +import styles from './uploadsGalleryModalStyles'; +import { MediaItem } from '../../../providers/ecency/ecency.types'; +import { useIntl } from 'react-intl'; + +interface Props { + item: MediaItem; + insertedMediaUrls: string[], + isDeleteMode: boolean; + isDeleting: boolean; + deleteIds: string[]; + isExpandedMode: boolean; + onPress: () => void; +} + +export const MediaPreviewItem = ({ item, insertedMediaUrls, isDeleteMode, isDeleting, deleteIds, isExpandedMode, onPress }: Props) => { + + const intl = useIntl(); + + const thumbUrl = + item.thumbUrl || + proxifyImageSrc(item.url, 600, 500, Platform.OS === 'ios' ? 'match' : 'webp'); + let isInsertedTimes = 0; + insertedMediaUrls?.forEach((url) => (isInsertedTimes += url === item.url ? 1 : 0)); + const isToBeDeleted = deleteIds.indexOf(item._id) >= 0; + const transformStyle = { + transform: isToBeDeleted ? [{ scaleX: 0.7 }, { scaleY: 0.7 }] : [], + }; + + const _renderStatus = () => (item.speakData && + + {intl.formatMessage({id:`uploads_modal.${item.speakData?.status}`})} + + ) + + const _renderMinus = () => + isDeleteMode && ( + + + + ); + + const _renderCounter = () => + isInsertedTimes > 0 && + !isDeleteMode && ( + + {isInsertedTimes} + + ); + + return ( + + + + {_renderCounter()} + {_renderMinus()} + {_renderStatus()} + + + ); +} \ No newline at end of file diff --git a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx index 5f9ade7ea..09332a7f3 100644 --- a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx +++ b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx @@ -28,6 +28,7 @@ import styles, { } from './uploadsGalleryModalStyles'; import { editorQueries } from '../../../providers/queries'; import { MediaItem } from '../../../providers/ecency/ecency.types'; +import { MediaPreviewItem } from './mediaPreviewItem'; type Props = { insertedMediaUrls: string[]; @@ -102,6 +103,7 @@ const UploadsGalleryContent = ({ // render list item for snippet and handle actions; const _renderItem = ({ item, index }: { item: MediaItem; index: number }) => { + const _onPress = () => { if (isDeleteMode) { const idIndex = deleteIds.indexOf(item._id); @@ -116,48 +118,14 @@ const UploadsGalleryContent = ({ } }; - const thumbUrl = - item.thumbUrl || - proxifyImageSrc(item.url, 600, 500, Platform.OS === 'ios' ? 'match' : 'webp'); - let isInsertedTimes = 0; - insertedMediaUrls?.forEach((url) => (isInsertedTimes += url === item.url ? 1 : 0)); - const isToBeDeleted = deleteIds.indexOf(item._id) >= 0; - const transformStyle = { - transform: isToBeDeleted ? [{ scaleX: 0.7 }, { scaleY: 0.7 }] : [], - }; - - const _renderMinus = () => - isDeleteMode && ( - - - - ); - - const _renderCounter = () => - isInsertedTimes > 0 && - !isDeleteMode && ( - - {isInsertedTimes} - - ); - - return ( - - - - {_renderCounter()} - {_renderMinus()} - - - ); + return }; const _renderSelectButton = (iconName: string, text: string, onPress: () => void) => { diff --git a/src/components/uploadsGalleryModal/children/uploadsGalleryModalStyles.ts b/src/components/uploadsGalleryModal/children/uploadsGalleryModalStyles.ts index 95c043a53..813b93679 100644 --- a/src/components/uploadsGalleryModal/children/uploadsGalleryModalStyles.ts +++ b/src/components/uploadsGalleryModal/children/uploadsGalleryModalStyles.ts @@ -205,6 +205,25 @@ export default EStyleSheet.create({ fontSize: 16, } as TextStyle, + statusContainer: { + backgroundColor: '$primaryBlue', + position: 'absolute', + bottom: 0, + left: 8, + right: 0, + borderBottomLeftRadius: 16, + borderBottomRightRadius: 16, + padding: 2, + height: 20, + justifyContent: 'center', + alignItems:'center' + } as ViewStyle, + + statusText: { + color: '$pureWhite', + fontSize: 14, + } as TextStyle, + checkStyle: { backgroundColor: '$white', } as ViewStyle, diff --git a/src/config/locales/en-US.json b/src/config/locales/en-US.json index f99f422c5..0b2028bf4 100644 --- a/src/config/locales/en-US.json +++ b/src/config/locales/en-US.json @@ -560,7 +560,11 @@ "confirm_delete":"Are you sure you want to delete images from your uploads", "message_failed":"Failed to upload image", "delete_failed":"Failed to delete image", - "failed_count":"Failed to upload {failedCount} of {totalCount} selected image(s)" + "failed_count":"Failed to upload {failedCount} of {totalCount} selected image(s)", + "publish_manual":"Ready", + "published":"Published", + "encoding_ipfs":"Encoding", + "deleted":"Deleted" }, "pincode": { "enter_text": "Enter PIN to unlock", diff --git a/src/providers/queries/editorQueries/speakQueries.ts b/src/providers/queries/editorQueries/speakQueries.ts index efe0b163e..fa0a6d1ea 100644 --- a/src/providers/queries/editorQueries/speakQueries.ts +++ b/src/providers/queries/editorQueries/speakQueries.ts @@ -1,13 +1,14 @@ -import { useQuery } from "@tanstack/react-query"; +import { QueryKey, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useIntl } from "react-intl"; import { useAppDispatch, useAppSelector } from "../../../hooks"; import { toastNotification } from "../../../redux/actions/uiAction"; import { MediaItem } from "../../ecency/ecency.types"; -import { getAllVideoStatuses } from "../../speak/speak"; +import { getAllVideoStatuses, markAsPublished } from "../../speak/speak"; import QUERIES from "../queryKeys"; import { extract3SpeakIds } from "../../../utils/editor"; import { useRef } from "react"; import { ThreeSpeakStatus, ThreeSpeakVideo } from "../../speak/speak.types"; +import bugsnapInstance from "../../../config/bugsnag"; /** * fetches and caches speak video uploads @@ -16,38 +17,38 @@ import { ThreeSpeakStatus, ThreeSpeakVideo } from "../../speak/speak.types"; export const useVideoUploadsQuery = () => { const intl = useIntl(); const dispatch = useAppDispatch(); - + const currentAccount = useAppSelector((state) => state.account.currentAccount); const pinHash = useAppSelector((state) => state.application.pin); - + const _fetchVideoUploads = async () => getAllVideoStatuses(currentAccount, pinHash); - + // TOOD: filter cache data for post edits to only show already published videos - + return useQuery([QUERIES.MEDIA.GET_VIDEOS], _fetchVideoUploads, { - initialData: [], - onError: () => { - dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); - }, + initialData: [], + onError: () => { + dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); + }, }); - }; +}; export const useSpeakContentBuilder = () => { const videoUploads = useVideoUploadsQuery(); - const videoPublishMetaRef = useRef(null); + const videoPublishMetaRef = useRef(null); - const build = (body:string) => { + const build = (body: string) => { let _newBody = body; - const _ids = extract3SpeakIds({body}); + const _ids = extract3SpeakIds({ body }); _ids.forEach((id) => { - const mediaItem:MediaItem|undefined = videoUploads.data.find((item) => item._id === id); - if(mediaItem){ + const mediaItem: MediaItem | undefined = videoUploads.data.find((item) => item._id === id); + if (mediaItem) { //check if video is unpublished, set unpublish video meta - if(!videoPublishMetaRef.current && mediaItem.speakData?.status === ThreeSpeakStatus.READY){ + if (!videoPublishMetaRef.current && mediaItem.speakData?.status === ThreeSpeakStatus.READY) { videoPublishMetaRef.current = mediaItem.speakData; } @@ -55,7 +56,7 @@ export const useSpeakContentBuilder = () => { const _toReplaceStr = `[3speak](${id})`; const _replacement = `
[![](${mediaItem.thumbUrl})](${mediaItem.url})
` _newBody = _newBody.replace(_toReplaceStr, _replacement) - + } }) @@ -64,6 +65,73 @@ export const useSpeakContentBuilder = () => { return { build, - videoPublishMeta:videoPublishMetaRef.current + videoPublishMeta: videoPublishMetaRef.current } -} \ No newline at end of file +} + + + +export const useSpeakMutations = () => { + const intl = useIntl(); + const dispatch = useAppDispatch(); + const queryClient = useQueryClient(); + + const currentAccount = useAppSelector((state) => state.account.currentAccount); + const pinCode = useAppSelector((state) => state.application.pin); + + // id is options, if no id is provided program marks all notifications as read; + const _mutationFn = async (id: string) => { + try { + const response = await markAsPublished(currentAccount, pinCode, id); + console.log('Speak video marked as published', response); + + return true; + } catch (err) { + bugsnapInstance.notify(err); + } + }; + + const _options: UseMutationOptions = { + onMutate: async (videoId) => { + // TODO: find a way to optimise mutations by avoiding too many loops + console.log('on mutate data', videoId); + + // update query data + const videosCache: MediaItem[] | undefined = queryClient.getQueryData([ + QUERIES.MEDIA.GET_VIDEOS, + ]); + console.log('query data', videosCache); + + if(!videosCache){ + return; + } + + const _vidIndex = videosCache.findIndex((item) => item._id === videoId); + + if(_vidIndex){ + const spkData = videosCache[_vidIndex].speakData; + if(spkData){ + spkData.status = ThreeSpeakStatus.PUBLISHED; + } + } + + + queryClient.setQueryData([QUERIES.MEDIA.GET_VIDEOS], videosCache) + }, + + onSuccess: async (status, _id) => { + console.log('on success data', status); + queryClient.invalidateQueries([QUERIES.MEDIA.GET_VIDEOS]); + + }, + onError: () => { + dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); + }, + }; + + const markAsPublishedMutation = useMutation(_mutationFn, _options); + + return { + markAsPublishedMutation + } +}; \ No newline at end of file diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 903b22969..f609809fa 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -599,7 +599,7 @@ class EditorContainer extends Component { pinCode, userActivityMutation, speakContentBuilder, - // isDefaultFooter, + speakMutations, } = this.props; const { rewardType, isPostSending, thumbUrl, draftId, shouldReblog } = this.state; @@ -703,7 +703,8 @@ class EditorContainer extends Component { } - //TODO: mark unpublished video as published on 3speak if that is the case + //mark unpublished video as published on 3speak if that is the case + speakMutations.markAsPublishedMutation.mutate(speakContentBuilder.videoPublishMeta._id) // post publish updates dispatch(deleteDraftCacheEntry(DEFAULT_USER_DRAFT_ID + currentAccount.name)); @@ -1259,6 +1260,7 @@ const mapStateToProps = (state) => ({ const mapQueriesToProps = () => ({ queryClient: useQueryClient(), speakContentBuilder: speakQueries.useSpeakContentBuilder(), + speakMutations: speakQueries.useSpeakMutations(), userActivityMutation: useUserActivityMutation(), postCachePrimer: usePostsCachePrimer(), }); From 3139a00061e5f235cdb7c2003b33af2d3967c1c0 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Wed, 15 Nov 2023 17:31:45 +0500 Subject: [PATCH 059/111] added multiple unpublished video fail safe --- .../queries/editorQueries/speakQueries.ts | 19 ++++++++++++++++--- .../editor/container/editorContainer.tsx | 14 ++++++++++---- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/providers/queries/editorQueries/speakQueries.ts b/src/providers/queries/editorQueries/speakQueries.ts index fa0a6d1ea..6fc063d7d 100644 --- a/src/providers/queries/editorQueries/speakQueries.ts +++ b/src/providers/queries/editorQueries/speakQueries.ts @@ -1,7 +1,7 @@ import { QueryKey, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useIntl } from "react-intl"; import { useAppDispatch, useAppSelector } from "../../../hooks"; -import { toastNotification } from "../../../redux/actions/uiAction"; +import { showActionModal, toastNotification } from "../../../redux/actions/uiAction"; import { MediaItem } from "../../ecency/ecency.types"; import { getAllVideoStatuses, markAsPublished } from "../../speak/speak"; import QUERIES from "../queryKeys"; @@ -9,6 +9,7 @@ import { extract3SpeakIds } from "../../../utils/editor"; import { useRef } from "react"; import { ThreeSpeakStatus, ThreeSpeakVideo } from "../../speak/speak.types"; import bugsnapInstance from "../../../config/bugsnag"; +import { useDispatch } from "react-redux"; /** * fetches and caches speak video uploads @@ -36,11 +37,13 @@ export const useVideoUploadsQuery = () => { export const useSpeakContentBuilder = () => { + const dispatch = useDispatch(); const videoUploads = useVideoUploadsQuery(); const videoPublishMetaRef = useRef(null); const build = (body: string) => { let _newBody = body; + videoPublishMetaRef.current = null; const _ids = extract3SpeakIds({ body }); _ids.forEach((id) => { @@ -48,8 +51,18 @@ export const useSpeakContentBuilder = () => { if (mediaItem) { //check if video is unpublished, set unpublish video meta - if (!videoPublishMetaRef.current && mediaItem.speakData?.status === ThreeSpeakStatus.READY) { - videoPublishMetaRef.current = mediaItem.speakData; + if (mediaItem.speakData?.status === ThreeSpeakStatus.READY) { + if(!videoPublishMetaRef.current){ + videoPublishMetaRef.current = mediaItem.speakData; + } else { + dispatch(showActionModal({ + title:"Fail", + body:"Can have only one unpublished video per post", + + })) + throw new Error("Fail") + } + } //replace 3speak with actual data diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index f609809fa..194be0876 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -35,7 +35,6 @@ import { createPatch, extract3SpeakIds, } from '../../../utils/editor'; -// import { generateSignature } from '../../../utils/image'; // Component import EditorScreen from '../screen/editorScreen'; @@ -610,14 +609,21 @@ class EditorContainer extends Component { } if (currentAccount) { + + // build speak video body + try{ + fields.body = speakContentBuilder.build(fields.body); + } catch(err){ + console.warn("fail", err); + return; + } + + this.setState({ isPostSending: true, }); - // build speak video body - fields.body = speakContentBuilder.build(fields.body); - // only require video meta for unpublished video, it will always be one const meta = await extractMetadata({ body: fields.body, From 03007725726a83c0f44567976ca5a1573c6da66a Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Wed, 15 Nov 2023 18:44:46 +0500 Subject: [PATCH 060/111] updated counter for inserted videos and images --- .../markdownEditor/children/editorToolbar.tsx | 8 +++--- .../view/markdownEditorView.tsx | 9 ++----- .../children/uploadsGalleryModalStyles.ts | 2 +- .../container/uploadsGalleryModal.tsx | 27 ++++++++++++++++--- 4 files changed, 30 insertions(+), 16 deletions(-) diff --git a/src/components/markdownEditor/children/editorToolbar.tsx b/src/components/markdownEditor/children/editorToolbar.tsx index 126202a3d..8944b76d3 100644 --- a/src/components/markdownEditor/children/editorToolbar.tsx +++ b/src/components/markdownEditor/children/editorToolbar.tsx @@ -15,7 +15,7 @@ import { MediaInsertData, Modes } from '../../uploadsGalleryModal/container/uplo import Formats from './formats/formats'; type Props = { - insertedMediaUrls: string[]; + postBody: string; paramFiles: any[]; isEditing: boolean; isPreviewActive: boolean; @@ -28,7 +28,7 @@ type Props = { }; export const EditorToolbar = ({ - insertedMediaUrls, + postBody, paramFiles, isEditing, isPreviewActive, @@ -58,7 +58,7 @@ export const EditorToolbar = ({ }); // TODO: set to false before PR - _showUploadsExtension(); + _showUploadsExtension(Modes.MODE_VIDEO); return () => { keyboardDidHideListener.remove(); @@ -202,7 +202,7 @@ export const EditorToolbar = ({ {isExtensionVisible && } (null); const clearRef = useRef(null); @@ -192,10 +190,7 @@ const MarkdownEditorView = ({ setIsEditing(false); handleBodyChange(bodyTextRef.current); handleFormUpdate('body', bodyTextRef.current); - const urls = extractImageUrls({ body: bodyTextRef.current }); - if (urls.length !== insertedMediaUrls.length) { - setInsertedMediaUrls(urls); - } + }, 500), [], ); @@ -437,7 +432,7 @@ const MarkdownEditorView = ({ {_renderFloatingDraftButton()} (Modes.MODE_IMAGE); + const [mediaUrls, setMediaUrls] = useState([]); const isLoggedIn = useAppSelector((state) => state.application.isLoggedIn); @@ -149,6 +150,24 @@ export const UploadsGalleryModal = forwardRef( _getMediaUploads(mode); // get media uploads when there is new update }, [mediaUploadsQuery.data, mode]); + useEffect(() => { + if (showModal) { + let _urls: string[] = [] + if (mode === Modes.MODE_VIDEO) { + const _vidIds = extract3SpeakIds({ body: postBody }) + _urls = _vidIds.map((id) => { + const mediaItem = mediaUploadsQuery.data.find(item => item._id === id) + return mediaItem?.url; + }) + } else { + _urls = extractImageUrls({ body: postBody }) + } + setMediaUrls(_urls) + Alert.alert('asdf', _urls.length + '') + + } + }, [postBody, showModal, mode]) + const _handleOpenImagePicker = (addToUploads?: boolean) => { ImagePicker.openPicker({ includeBase64: true, @@ -402,7 +421,7 @@ export const UploadsGalleryModal = forwardRef( !isPreviewActive && showModal && ( Date: Wed, 15 Nov 2023 18:45:31 +0500 Subject: [PATCH 061/111] remove test alert --- .../uploadsGalleryModal/container/uploadsGalleryModal.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index ef5d1c004..ed2c7889f 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -163,7 +163,6 @@ export const UploadsGalleryModal = forwardRef( _urls = extractImageUrls({ body: postBody }) } setMediaUrls(_urls) - Alert.alert('asdf', _urls.length + '') } }, [postBody, showModal, mode]) From 6e60a612ee63e0d5d12649375e7a0c22f8e04aea Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Wed, 15 Nov 2023 19:20:47 +0500 Subject: [PATCH 062/111] added beneficiary todo --- src/screens/editor/container/editorContainer.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 194be0876..cd78e5314 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -602,6 +602,8 @@ class EditorContainer extends Component { } = this.props; const { rewardType, isPostSending, thumbUrl, draftId, shouldReblog } = this.state; + //TODO: handle appropriate speak beneficiaries if needed + //ref: https://swimlanes.io/u/7xPWxOvpH const beneficiaries = this._extractBeneficiaries(); if (isPostSending) { From b25035c55ceca35a3c0f83a4cb6c8b831bcbae68 Mon Sep 17 00:00:00 2001 From: Nouman Tahir Date: Thu, 16 Nov 2023 16:11:36 +0500 Subject: [PATCH 063/111] setting beneficiaries for ubpublished video, added redundency during post publishing --- .../beneficiarySelectionContent.tsx | 5 +- .../markdownEditor/children/editorToolbar.tsx | 3 + .../view/markdownEditorView.tsx | 39 +++++------ .../children/uploadsGalleryContent.tsx | 64 +++++++++++++++---- .../container/uploadsGalleryModal.tsx | 3 + src/providers/speak/constants.ts | 15 +++++ src/providers/speak/speak.ts | 1 + .../editor/container/editorContainer.tsx | 22 +++++-- src/screens/editor/screen/editorScreen.tsx | 1 + 9 files changed, 112 insertions(+), 41 deletions(-) diff --git a/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx b/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx index dc9d41fff..2f883d7df 100644 --- a/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx +++ b/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx @@ -12,6 +12,7 @@ import { lookupAccounts } from '../../providers/hive/dhive'; import { setBeneficiaries as setBeneficiariesAction } from '../../redux/actions/editorActions'; import { TEMP_BENEFICIARIES_ID } from '../../redux/constants/constants'; import { Beneficiary } from '../../redux/reducers/editorReducer'; +import { BENEFICIARY_SRC_ENCODER } from '../../providers/speak/constants'; interface BeneficiarySelectionContentProps { draftId: string; @@ -59,9 +60,7 @@ const BeneficiarySelectionContent = ({ }, [powerDownBeneficiaries]); useEffect(() => { - if (draftId) { readTempBeneficiaries(); - } }, [draftId]); useEffect(() => { @@ -344,7 +343,7 @@ const BeneficiarySelectionContent = ({ wrapperStyle={styles.usernameFormInputWrapper} /> - {!_isCurrentUser ? ( + {!_isCurrentUser && item.src !== BENEFICIARY_SRC_ENCODER ? ( {isExtensionVisible && } { const intl = useIntl(); + const dispatch = useDispatch(); const deleteMediaMutation = editorQueries.useMediaDeleteMutation(); @@ -114,17 +119,48 @@ const UploadsGalleryContent = ({ } setDeleteIds([...deleteIds]); } else { - insertMedia(new Map([[index, true]])); + + let isUnpublishedInserted = false + if (item.speakData && item.speakData.status !== ThreeSpeakStatus.PUBLISHED) { + //make sure this is not the second ubpublished video being inserted + + insertedMediaUrls.forEach((url) => { + const _mediaItem = mediaUploads.find((item) => (item.url === url && item.speakData?.status !== ThreeSpeakStatus.PUBLISHED)); + if (_mediaItem) { + isUnpublishedInserted = true; + } + }) + + if (!isUnpublishedInserted) { + //update beneficiaries + const vidBeneficiaries = JSON.parse(item.speakData.beneficiaries || '[]') + const beneficiaries = [...DEFAULT_SPEAK_BENEFICIARIES, ...vidBeneficiaries] + const _draftId = draftId || TEMP_BENEFICIARIES_ID; + Alert.alert(_draftId, JSON.stringify(beneficiaries)) + dispatch(setBeneficiaries(_draftId, beneficiaries)) + } + } + + //TOOD: later handle beneficiaries removal on item deletion from body + if(!isUnpublishedInserted){ + insertMedia(new Map([[index, true]])); + } else { + dispatch(showActionModal({ + title:"Fail", + body:"Can only have one unpublished video per post" + })) + } + } }; - return }; diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index ed2c7889f..97248dcf3 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -48,6 +48,7 @@ export interface MediaInsertData { } interface UploadsGalleryModalProps { + draftId?: string; postBody: string; paramFiles: any[]; isEditing: boolean; @@ -61,6 +62,7 @@ interface UploadsGalleryModalProps { export const UploadsGalleryModal = forwardRef( ( { + draftId, postBody, paramFiles, isEditing, @@ -420,6 +422,7 @@ export const UploadsGalleryModal = forwardRef( !isPreviewActive && showModal && ( { try { const response = await speakApi.get( diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index cd78e5314..4fa5c84d1 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -20,6 +20,7 @@ import { reblog, postComment, } from '../../../providers/hive/dhive'; +import unionBy from 'lodash/unionBy'; // Constants import { default as ROUTES } from '../../../constants/routeNames'; @@ -52,6 +53,7 @@ import { PointActivityIds } from '../../../providers/ecency/ecency.types'; import { usePostsCachePrimer } from '../../../providers/queries/postQueries/postQueries'; import { PostTypes } from '../../../constants/postTypes'; import { speakQueries } from '../../../providers/queries'; +import { BENEFICIARY_SRC_ENCODER, DEFAULT_SPEAK_BENEFICIARIES } from '../../../providers/speak/constants'; /* * Props Name Description Value @@ -602,9 +604,9 @@ class EditorContainer extends Component { } = this.props; const { rewardType, isPostSending, thumbUrl, draftId, shouldReblog } = this.state; - //TODO: handle appropriate speak beneficiaries if needed + //ref: https://swimlanes.io/u/7xPWxOvpH - const beneficiaries = this._extractBeneficiaries(); + let beneficiaries = this._extractBeneficiaries(); if (isPostSending) { return; @@ -613,13 +615,23 @@ class EditorContainer extends Component { if (currentAccount) { // build speak video body - try{ + try { fields.body = speakContentBuilder.build(fields.body); - } catch(err){ + + //verify and video beneficiaries redundent + if (!speakContentBuilder.videoPublishMeta) { + beneficiaries = beneficiaries.filter(item => item.src !== BENEFICIARY_SRC_ENCODER); + } else { + const encoderBene = [ + ...JSON.parse(speakContentBuilder.videoPublishMeta.beneficiaries || []), + ...DEFAULT_SPEAK_BENEFICIARIES]; + beneficiaries = unionBy(encoderBene, beneficiaries, 'account'); + } + } catch (err) { console.warn("fail", err); return; } - + this.setState({ isPostSending: true, diff --git a/src/screens/editor/screen/editorScreen.tsx b/src/screens/editor/screen/editorScreen.tsx index 297470766..b18fac7a5 100644 --- a/src/screens/editor/screen/editorScreen.tsx +++ b/src/screens/editor/screen/editorScreen.tsx @@ -495,6 +495,7 @@ class EditorScreen extends Component { /> )} Date: Thu, 16 Nov 2023 16:12:47 +0500 Subject: [PATCH 064/111] lint --- .../beneficiarySelectionContent.tsx | 2 +- .../markdownEditor/children/editorToolbar.tsx | 2 +- .../view/markdownEditorView.tsx | 1 - .../children/mediaPreviewItem.tsx | 140 +++++----- .../children/uploadsGalleryContent.tsx | 69 +++-- .../children/uploadsGalleryModalStyles.ts | 2 +- .../container/uploadsGalleryModal.tsx | 27 +- .../queries/editorQueries/editorQueries.ts | 4 - .../queries/editorQueries/speakQueries.ts | 244 +++++++++--------- src/providers/speak/constants.ts | 24 +- src/providers/speak/speak.ts | 1 - src/providers/speak/speak.types.ts | 3 +- .../editor/container/editorContainer.tsx | 47 ++-- src/utils/editor.ts | 2 +- 14 files changed, 276 insertions(+), 292 deletions(-) diff --git a/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx b/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx index 2f883d7df..a1ad1066b 100644 --- a/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx +++ b/src/components/beneficiarySelectionContent/beneficiarySelectionContent.tsx @@ -60,7 +60,7 @@ const BeneficiarySelectionContent = ({ }, [powerDownBeneficiaries]); useEffect(() => { - readTempBeneficiaries(); + readTempBeneficiaries(); }, [draftId]); useEffect(() => { diff --git a/src/components/markdownEditor/children/editorToolbar.tsx b/src/components/markdownEditor/children/editorToolbar.tsx index 76b14281c..a1c6a77ad 100644 --- a/src/components/markdownEditor/children/editorToolbar.tsx +++ b/src/components/markdownEditor/children/editorToolbar.tsx @@ -15,7 +15,7 @@ import { MediaInsertData, Modes } from '../../uploadsGalleryModal/container/uplo import Formats from './formats/formats'; type Props = { - draftId?:string; + draftId?: string; postBody: string; paramFiles: any[]; isEditing: boolean; diff --git a/src/components/markdownEditor/view/markdownEditorView.tsx b/src/components/markdownEditor/view/markdownEditorView.tsx index 54faf57f3..dced6a682 100644 --- a/src/components/markdownEditor/view/markdownEditorView.tsx +++ b/src/components/markdownEditor/view/markdownEditorView.tsx @@ -190,7 +190,6 @@ const MarkdownEditorView = ({ setIsEditing(false); handleBodyChange(bodyTextRef.current); handleFormUpdate('body', bodyTextRef.current); - }, 500), [], ); diff --git a/src/components/uploadsGalleryModal/children/mediaPreviewItem.tsx b/src/components/uploadsGalleryModal/children/mediaPreviewItem.tsx index 072cecf01..08ed6efec 100644 --- a/src/components/uploadsGalleryModal/children/mediaPreviewItem.tsx +++ b/src/components/uploadsGalleryModal/children/mediaPreviewItem.tsx @@ -1,84 +1,84 @@ - import React from 'react'; import { proxifyImageSrc } from '@ecency/render-helper'; -import { - Platform, - Text, - TouchableOpacity, - View -} from 'react-native'; +import { Platform, Text, TouchableOpacity, View } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; import FastImage from 'react-native-fast-image'; -import { - default as AnimatedView, - ZoomIn -} from 'react-native-reanimated'; +import { default as AnimatedView, ZoomIn } from 'react-native-reanimated'; +import { useIntl } from 'react-intl'; import { Icon } from '../..'; import styles from './uploadsGalleryModalStyles'; import { MediaItem } from '../../../providers/ecency/ecency.types'; -import { useIntl } from 'react-intl'; interface Props { - item: MediaItem; - insertedMediaUrls: string[], - isDeleteMode: boolean; - isDeleting: boolean; - deleteIds: string[]; - isExpandedMode: boolean; - onPress: () => void; + item: MediaItem; + insertedMediaUrls: string[]; + isDeleteMode: boolean; + isDeleting: boolean; + deleteIds: string[]; + isExpandedMode: boolean; + onPress: () => void; } -export const MediaPreviewItem = ({ item, insertedMediaUrls, isDeleteMode, isDeleting, deleteIds, isExpandedMode, onPress }: Props) => { +export const MediaPreviewItem = ({ + item, + insertedMediaUrls, + isDeleteMode, + isDeleting, + deleteIds, + isExpandedMode, + onPress, +}: Props) => { + const intl = useIntl(); - const intl = useIntl(); + const thumbUrl = + item.thumbUrl || proxifyImageSrc(item.url, 600, 500, Platform.OS === 'ios' ? 'match' : 'webp'); + let isInsertedTimes = 0; + insertedMediaUrls?.forEach((url) => (isInsertedTimes += url === item.url ? 1 : 0)); + const isToBeDeleted = deleteIds.indexOf(item._id) >= 0; + const transformStyle = { + transform: isToBeDeleted ? [{ scaleX: 0.7 }, { scaleY: 0.7 }] : [], + }; - const thumbUrl = - item.thumbUrl || - proxifyImageSrc(item.url, 600, 500, Platform.OS === 'ios' ? 'match' : 'webp'); - let isInsertedTimes = 0; - insertedMediaUrls?.forEach((url) => (isInsertedTimes += url === item.url ? 1 : 0)); - const isToBeDeleted = deleteIds.indexOf(item._id) >= 0; - const transformStyle = { - transform: isToBeDeleted ? [{ scaleX: 0.7 }, { scaleY: 0.7 }] : [], - }; - - const _renderStatus = () => (item.speakData && - - {intl.formatMessage({id:`uploads_modal.${item.speakData?.status}`})} - - ) - - const _renderMinus = () => - isDeleteMode && ( - - - - ); - - const _renderCounter = () => - isInsertedTimes > 0 && - !isDeleteMode && ( - - {isInsertedTimes} - - ); - - return ( - - - - {_renderCounter()} - {_renderMinus()} - {_renderStatus()} - - + const _renderStatus = () => + item.speakData && ( + + + {intl.formatMessage({ id: `uploads_modal.${item.speakData?.status}` })} + + ); -} \ No newline at end of file + + const _renderMinus = () => + isDeleteMode && ( + + + + ); + + const _renderCounter = () => + isInsertedTimes > 0 && + !isDeleteMode && ( + + {isInsertedTimes} + + ); + + return ( + + + + {_renderCounter()} + {_renderMinus()} + {_renderStatus()} + + + ); +}; diff --git a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx index bd83cbdaf..8b44764d0 100644 --- a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx +++ b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx @@ -1,13 +1,6 @@ import React, { useEffect, useRef, useState } from 'react'; import { useIntl } from 'react-intl'; -import { - ActivityIndicator, - Alert, - Keyboard, - Text, - TouchableOpacity, - View -} from 'react-native'; +import { ActivityIndicator, Alert, Keyboard, Text, TouchableOpacity, View } from 'react-native'; import EStyleSheet from 'react-native-extended-stylesheet'; import { FlatList } from 'react-native-gesture-handler'; import Animated, { @@ -16,6 +9,7 @@ import Animated, { SlideInRight, SlideOutRight, } from 'react-native-reanimated'; +import { useDispatch } from 'react-redux'; import { Icon, IconButton } from '../..'; import { MediaItem } from '../../../providers/ecency/ecency.types'; import { editorQueries } from '../../../providers/queries'; @@ -26,7 +20,6 @@ import styles, { MAX_HORIZONTAL_THUMBS, } from './uploadsGalleryModalStyles'; import { ThreeSpeakStatus } from '../../../providers/speak/speak.types'; -import { useDispatch } from 'react-redux'; import { setBeneficiaries } from '../../../redux/actions/editorActions'; import { TEMP_BENEFICIARIES_ID } from '../../../redux/constants/constants'; import { DEFAULT_SPEAK_BENEFICIARIES } from '../../../providers/speak/constants'; @@ -108,7 +101,6 @@ const UploadsGalleryContent = ({ // render list item for snippet and handle actions; const _renderItem = ({ item, index }: { item: MediaItem; index: number }) => { - const _onPress = () => { if (isDeleteMode) { const idIndex = deleteIds.indexOf(item._id); @@ -119,49 +111,54 @@ const UploadsGalleryContent = ({ } setDeleteIds([...deleteIds]); } else { - - let isUnpublishedInserted = false + let isUnpublishedInserted = false; if (item.speakData && item.speakData.status !== ThreeSpeakStatus.PUBLISHED) { - //make sure this is not the second ubpublished video being inserted - + // make sure this is not the second ubpublished video being inserted + insertedMediaUrls.forEach((url) => { - const _mediaItem = mediaUploads.find((item) => (item.url === url && item.speakData?.status !== ThreeSpeakStatus.PUBLISHED)); + const _mediaItem = mediaUploads.find( + (item) => item.url === url && item.speakData?.status !== ThreeSpeakStatus.PUBLISHED, + ); if (_mediaItem) { isUnpublishedInserted = true; } - }) + }); if (!isUnpublishedInserted) { - //update beneficiaries - const vidBeneficiaries = JSON.parse(item.speakData.beneficiaries || '[]') - const beneficiaries = [...DEFAULT_SPEAK_BENEFICIARIES, ...vidBeneficiaries] + // update beneficiaries + const vidBeneficiaries = JSON.parse(item.speakData.beneficiaries || '[]'); + const beneficiaries = [...DEFAULT_SPEAK_BENEFICIARIES, ...vidBeneficiaries]; const _draftId = draftId || TEMP_BENEFICIARIES_ID; - Alert.alert(_draftId, JSON.stringify(beneficiaries)) - dispatch(setBeneficiaries(_draftId, beneficiaries)) + Alert.alert(_draftId, JSON.stringify(beneficiaries)); + dispatch(setBeneficiaries(_draftId, beneficiaries)); } } - //TOOD: later handle beneficiaries removal on item deletion from body - if(!isUnpublishedInserted){ + // TOOD: later handle beneficiaries removal on item deletion from body + if (!isUnpublishedInserted) { insertMedia(new Map([[index, true]])); } else { - dispatch(showActionModal({ - title:"Fail", - body:"Can only have one unpublished video per post" - })) + dispatch( + showActionModal({ + title: 'Fail', + body: 'Can only have one unpublished video per post', + }), + ); } - } }; - return + return ( + + ); }; const _renderSelectButton = (iconName: string, text: string, onPress: () => void) => { diff --git a/src/components/uploadsGalleryModal/children/uploadsGalleryModalStyles.ts b/src/components/uploadsGalleryModal/children/uploadsGalleryModalStyles.ts index 424d59dae..65cda3c1f 100644 --- a/src/components/uploadsGalleryModal/children/uploadsGalleryModalStyles.ts +++ b/src/components/uploadsGalleryModal/children/uploadsGalleryModalStyles.ts @@ -216,7 +216,7 @@ export default EStyleSheet.create({ padding: 2, height: 20, justifyContent: 'center', - alignItems:'center' + alignItems: 'center', } as ViewStyle, statusText: { diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 97248dcf3..53c3b8336 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -15,12 +15,14 @@ import bugsnapInstance from '../../../config/bugsnag'; import UploadsGalleryContent from '../children/uploadsGalleryContent'; import { useAppDispatch, useAppSelector } from '../../../hooks'; -import { delay, extract3SpeakIds, extractFilenameFromPath, extractImageUrls } from '../../../utils/editor'; -import showLoginAlert from '../../../utils/showLoginAlert'; import { - editorQueries, - speakQueries, -} from '../../../providers/queries'; + delay, + extract3SpeakIds, + extractFilenameFromPath, + extractImageUrls, +} from '../../../utils/editor'; +import showLoginAlert from '../../../utils/showLoginAlert'; +import { editorQueries, speakQueries } from '../../../providers/queries'; import { showActionModal } from '../../../redux/actions/uiAction'; import { MediaItem } from '../../../providers/ecency/ecency.types'; @@ -154,20 +156,19 @@ export const UploadsGalleryModal = forwardRef( useEffect(() => { if (showModal) { - let _urls: string[] = [] + let _urls: string[] = []; if (mode === Modes.MODE_VIDEO) { - const _vidIds = extract3SpeakIds({ body: postBody }) + const _vidIds = extract3SpeakIds({ body: postBody }); _urls = _vidIds.map((id) => { - const mediaItem = mediaUploadsQuery.data.find(item => item._id === id) + const mediaItem = mediaUploadsQuery.data.find((item) => item._id === id); return mediaItem?.url; - }) + }); } else { - _urls = extractImageUrls({ body: postBody }) + _urls = extractImageUrls({ body: postBody }); } - setMediaUrls(_urls) - + setMediaUrls(_urls); } - }, [postBody, showModal, mode]) + }, [postBody, showModal, mode]); const _handleOpenImagePicker = (addToUploads?: boolean) => { ImagePicker.openPicker({ diff --git a/src/providers/queries/editorQueries/editorQueries.ts b/src/providers/queries/editorQueries/editorQueries.ts index 377bc41a4..3f20afd52 100644 --- a/src/providers/queries/editorQueries/editorQueries.ts +++ b/src/providers/queries/editorQueries/editorQueries.ts @@ -78,10 +78,6 @@ export const useAddToUploadsMutation = () => { }); }; - - - - export const useMediaUploadMutation = () => { const intl = useIntl(); const dispatch = useAppDispatch(); diff --git a/src/providers/queries/editorQueries/speakQueries.ts b/src/providers/queries/editorQueries/speakQueries.ts index 6fc063d7d..97579dc72 100644 --- a/src/providers/queries/editorQueries/speakQueries.ts +++ b/src/providers/queries/editorQueries/speakQueries.ts @@ -1,150 +1,142 @@ -import { QueryKey, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { useIntl } from "react-intl"; -import { useAppDispatch, useAppSelector } from "../../../hooks"; -import { showActionModal, toastNotification } from "../../../redux/actions/uiAction"; -import { MediaItem } from "../../ecency/ecency.types"; -import { getAllVideoStatuses, markAsPublished } from "../../speak/speak"; -import QUERIES from "../queryKeys"; -import { extract3SpeakIds } from "../../../utils/editor"; -import { useRef } from "react"; -import { ThreeSpeakStatus, ThreeSpeakVideo } from "../../speak/speak.types"; -import bugsnapInstance from "../../../config/bugsnag"; -import { useDispatch } from "react-redux"; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { useIntl } from 'react-intl'; +import { useRef } from 'react'; +import { useDispatch } from 'react-redux'; +import { useAppDispatch, useAppSelector } from '../../../hooks'; +import { showActionModal, toastNotification } from '../../../redux/actions/uiAction'; +import { MediaItem } from '../../ecency/ecency.types'; +import { getAllVideoStatuses, markAsPublished } from '../../speak/speak'; +import QUERIES from '../queryKeys'; +import { extract3SpeakIds } from '../../../utils/editor'; +import { ThreeSpeakStatus, ThreeSpeakVideo } from '../../speak/speak.types'; +import bugsnapInstance from '../../../config/bugsnag'; /** * fetches and caches speak video uploads * @returns query instance with data as array of videos as MediaItem[] */ export const useVideoUploadsQuery = () => { - const intl = useIntl(); - const dispatch = useAppDispatch(); + const intl = useIntl(); + const dispatch = useAppDispatch(); - const currentAccount = useAppSelector((state) => state.account.currentAccount); - const pinHash = useAppSelector((state) => state.application.pin); + const currentAccount = useAppSelector((state) => state.account.currentAccount); + const pinHash = useAppSelector((state) => state.application.pin); - const _fetchVideoUploads = async () => getAllVideoStatuses(currentAccount, pinHash); + const _fetchVideoUploads = async () => getAllVideoStatuses(currentAccount, pinHash); - // TOOD: filter cache data for post edits to only show already published videos + // TOOD: filter cache data for post edits to only show already published videos - return useQuery([QUERIES.MEDIA.GET_VIDEOS], _fetchVideoUploads, { - initialData: [], - onError: () => { - dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); - }, - }); + return useQuery([QUERIES.MEDIA.GET_VIDEOS], _fetchVideoUploads, { + initialData: [], + onError: () => { + dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); + }, + }); }; - export const useSpeakContentBuilder = () => { + const dispatch = useDispatch(); + const videoUploads = useVideoUploadsQuery(); + const videoPublishMetaRef = useRef(null); - const dispatch = useDispatch(); - const videoUploads = useVideoUploadsQuery(); - const videoPublishMetaRef = useRef(null); + const build = (body: string) => { + let _newBody = body; + videoPublishMetaRef.current = null; + const _ids = extract3SpeakIds({ body }); - const build = (body: string) => { - let _newBody = body; - videoPublishMetaRef.current = null; - const _ids = extract3SpeakIds({ body }); + _ids.forEach((id) => { + const mediaItem: MediaItem | undefined = videoUploads.data.find((item) => item._id === id); + if (mediaItem) { + // check if video is unpublished, set unpublish video meta + if (mediaItem.speakData?.status === ThreeSpeakStatus.READY) { + if (!videoPublishMetaRef.current) { + videoPublishMetaRef.current = mediaItem.speakData; + } else { + dispatch( + showActionModal({ + title: 'Fail', + body: 'Can have only one unpublished video per post', + }), + ); + throw new Error('Fail'); + } + } - _ids.forEach((id) => { - const mediaItem: MediaItem | undefined = videoUploads.data.find((item) => item._id === id); - if (mediaItem) { - - //check if video is unpublished, set unpublish video meta - if (mediaItem.speakData?.status === ThreeSpeakStatus.READY) { - if(!videoPublishMetaRef.current){ - videoPublishMetaRef.current = mediaItem.speakData; - } else { - dispatch(showActionModal({ - title:"Fail", - body:"Can have only one unpublished video per post", - - })) - throw new Error("Fail") - } - - } - - //replace 3speak with actual data - const _toReplaceStr = `[3speak](${id})`; - const _replacement = `
[![](${mediaItem.thumbUrl})](${mediaItem.url})
` - _newBody = _newBody.replace(_toReplaceStr, _replacement) - - } - }) - - return _newBody; - } - - return { - build, - videoPublishMeta: videoPublishMetaRef.current - } -} + // replace 3speak with actual data + const _toReplaceStr = `[3speak](${id})`; + const _replacement = `
[![](${mediaItem.thumbUrl})](${mediaItem.url})
`; + _newBody = _newBody.replace(_toReplaceStr, _replacement); + } + }); + return _newBody; + }; + return { + build, + videoPublishMeta: videoPublishMetaRef.current, + }; +}; export const useSpeakMutations = () => { - const intl = useIntl(); - const dispatch = useAppDispatch(); - const queryClient = useQueryClient(); + const intl = useIntl(); + const dispatch = useAppDispatch(); + const queryClient = useQueryClient(); - const currentAccount = useAppSelector((state) => state.account.currentAccount); - const pinCode = useAppSelector((state) => state.application.pin); + const currentAccount = useAppSelector((state) => state.account.currentAccount); + const pinCode = useAppSelector((state) => state.application.pin); - // id is options, if no id is provided program marks all notifications as read; - const _mutationFn = async (id: string) => { - try { - const response = await markAsPublished(currentAccount, pinCode, id); - console.log('Speak video marked as published', response); + // id is options, if no id is provided program marks all notifications as read; + const _mutationFn = async (id: string) => { + try { + const response = await markAsPublished(currentAccount, pinCode, id); + console.log('Speak video marked as published', response); - return true; - } catch (err) { - bugsnapInstance.notify(err); - } - }; - - const _options: UseMutationOptions = { - onMutate: async (videoId) => { - // TODO: find a way to optimise mutations by avoiding too many loops - console.log('on mutate data', videoId); - - // update query data - const videosCache: MediaItem[] | undefined = queryClient.getQueryData([ - QUERIES.MEDIA.GET_VIDEOS, - ]); - console.log('query data', videosCache); - - if(!videosCache){ - return; - } - - const _vidIndex = videosCache.findIndex((item) => item._id === videoId); - - if(_vidIndex){ - const spkData = videosCache[_vidIndex].speakData; - if(spkData){ - spkData.status = ThreeSpeakStatus.PUBLISHED; - } - } - - - queryClient.setQueryData([QUERIES.MEDIA.GET_VIDEOS], videosCache) - }, - - onSuccess: async (status, _id) => { - console.log('on success data', status); - queryClient.invalidateQueries([QUERIES.MEDIA.GET_VIDEOS]); - - }, - onError: () => { - dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); - }, - }; - - const markAsPublishedMutation = useMutation(_mutationFn, _options); - - return { - markAsPublishedMutation + return true; + } catch (err) { + bugsnapInstance.notify(err); } -}; \ No newline at end of file + }; + + const _options: UseMutationOptions = { + onMutate: async (videoId) => { + // TODO: find a way to optimise mutations by avoiding too many loops + console.log('on mutate data', videoId); + + // update query data + const videosCache: MediaItem[] | undefined = queryClient.getQueryData([ + QUERIES.MEDIA.GET_VIDEOS, + ]); + console.log('query data', videosCache); + + if (!videosCache) { + return; + } + + const _vidIndex = videosCache.findIndex((item) => item._id === videoId); + + if (_vidIndex) { + const spkData = videosCache[_vidIndex].speakData; + if (spkData) { + spkData.status = ThreeSpeakStatus.PUBLISHED; + } + } + + queryClient.setQueryData([QUERIES.MEDIA.GET_VIDEOS], videosCache); + }, + + onSuccess: async (status, _id) => { + console.log('on success data', status); + queryClient.invalidateQueries([QUERIES.MEDIA.GET_VIDEOS]); + }, + onError: () => { + dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); + }, + }; + + const markAsPublishedMutation = useMutation(_mutationFn, _options); + + return { + markAsPublishedMutation, + }; +}; diff --git a/src/providers/speak/constants.ts b/src/providers/speak/constants.ts index 3f4f2eded..24d7174c9 100644 --- a/src/providers/speak/constants.ts +++ b/src/providers/speak/constants.ts @@ -9,16 +9,16 @@ export const PATH_LOGIN = 'login'; export const PATH_API = 'api'; export const DEFAULT_SPEAK_BENEFICIARIES = [ - { - account: "spk.beneficiary", - src: "ENCODER_PAY", - weight: 900 - }, - { - account: "threespeakleader", - src: "ENCODER_PAY", - weight: 100 - } - ]; + { + account: 'spk.beneficiary', + src: 'ENCODER_PAY', + weight: 900, + }, + { + account: 'threespeakleader', + src: 'ENCODER_PAY', + weight: 100, + }, +]; -export const BENEFICIARY_SRC_ENCODER = 'ENCODER_PAY'; \ No newline at end of file +export const BENEFICIARY_SRC_ENCODER = 'ENCODER_PAY'; diff --git a/src/providers/speak/speak.ts b/src/providers/speak/speak.ts index f75c92782..1c47a9c66 100644 --- a/src/providers/speak/speak.ts +++ b/src/providers/speak/speak.ts @@ -12,7 +12,6 @@ const speakApi = axios.create({ baseURL: `${BASE_URL_SPEAK_STUDIO}/${PATH_MOBILE}`, }); - export const threespeakAuth = async (currentAccount: any, pinHash: string) => { try { const response = await speakApi.get( diff --git a/src/providers/speak/speak.types.ts b/src/providers/speak/speak.types.ts index faca0cab4..35ae9afe6 100644 --- a/src/providers/speak/speak.types.ts +++ b/src/providers/speak/speak.types.ts @@ -2,10 +2,9 @@ export enum ThreeSpeakStatus { PUBLISHED = 'published', READY = 'publish_manual', DELETED = 'deleted', - ENCODING = 'encoding_ipfs' + ENCODING = 'encoding_ipfs', } - export interface ThreeSpeakVideo { app: string; beneficiaries: string; // e.g. "[{\"account\":\"actifit-he\",\"weight\":100,\"src\":\"ENCODER_PAY\"}]" diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 4fa5c84d1..130276963 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -11,6 +11,7 @@ import { Buffer } from 'buffer'; import { useQueryClient } from '@tanstack/react-query'; import { gestureHandlerRootHOC } from 'react-native-gesture-handler'; import { postBodySummary } from '@ecency/render-helper'; +import unionBy from 'lodash/unionBy'; import { addDraft, updateDraft, getDrafts, addSchedule } from '../../../providers/ecency/ecency'; import { toastNotification, setRcOffer } from '../../../redux/actions/uiAction'; import { @@ -20,7 +21,6 @@ import { reblog, postComment, } from '../../../providers/hive/dhive'; -import unionBy from 'lodash/unionBy'; // Constants import { default as ROUTES } from '../../../constants/routeNames'; @@ -53,7 +53,10 @@ import { PointActivityIds } from '../../../providers/ecency/ecency.types'; import { usePostsCachePrimer } from '../../../providers/queries/postQueries/postQueries'; import { PostTypes } from '../../../constants/postTypes'; import { speakQueries } from '../../../providers/queries'; -import { BENEFICIARY_SRC_ENCODER, DEFAULT_SPEAK_BENEFICIARIES } from '../../../providers/speak/constants'; +import { + BENEFICIARY_SRC_ENCODER, + DEFAULT_SPEAK_BENEFICIARIES, +} from '../../../providers/speak/constants'; /* * Props Name Description Value @@ -604,8 +607,7 @@ class EditorContainer extends Component { } = this.props; const { rewardType, isPostSending, thumbUrl, draftId, shouldReblog } = this.state; - - //ref: https://swimlanes.io/u/7xPWxOvpH + // ref: https://swimlanes.io/u/7xPWxOvpH let beneficiaries = this._extractBeneficiaries(); if (isPostSending) { @@ -613,37 +615,35 @@ class EditorContainer extends Component { } if (currentAccount) { - // build speak video body try { fields.body = speakContentBuilder.build(fields.body); - //verify and video beneficiaries redundent + // verify and video beneficiaries redundent if (!speakContentBuilder.videoPublishMeta) { - beneficiaries = beneficiaries.filter(item => item.src !== BENEFICIARY_SRC_ENCODER); + beneficiaries = beneficiaries.filter((item) => item.src !== BENEFICIARY_SRC_ENCODER); } else { const encoderBene = [ - ...JSON.parse(speakContentBuilder.videoPublishMeta.beneficiaries || []), - ...DEFAULT_SPEAK_BENEFICIARIES]; + ...JSON.parse(speakContentBuilder.videoPublishMeta.beneficiaries || []), + ...DEFAULT_SPEAK_BENEFICIARIES, + ]; beneficiaries = unionBy(encoderBene, beneficiaries, 'account'); } } catch (err) { - console.warn("fail", err); + console.warn('fail', err); return; } - this.setState({ isPostSending: true, }); - // only require video meta for unpublished video, it will always be one const meta = await extractMetadata({ body: fields.body, thumbUrl, fetchRatios: true, - videoPublishMeta: speakContentBuilder.videoPublishMeta + videoPublishMeta: speakContentBuilder.videoPublishMeta, }); const _tags = fields.tags.filter((tag) => tag && tag !== ' '); @@ -722,9 +722,8 @@ class EditorContainer extends Component { }); } - - //mark unpublished video as published on 3speak if that is the case - speakMutations.markAsPublishedMutation.mutate(speakContentBuilder.videoPublishMeta._id) + // mark unpublished video as published on 3speak if that is the case + speakMutations.markAsPublishedMutation.mutate(speakContentBuilder.videoPublishMeta._id); // post publish updates dispatch(deleteDraftCacheEntry(DEFAULT_USER_DRAFT_ID + currentAccount.name)); @@ -764,8 +763,14 @@ class EditorContainer extends Component { }; _submitReply = async (fields) => { - const { currentAccount, pinCode, dispatch, userActivityMutation, draftsCollection, speakContentBuilder } = - this.props; + const { + currentAccount, + pinCode, + dispatch, + userActivityMutation, + draftsCollection, + speakContentBuilder, + } = this.props; const { isPostSending } = this.state; if (isPostSending) { @@ -789,8 +794,6 @@ class EditorContainer extends Component { const parentTags = post.json_metadata.tags; const draftId = `${currentAccount.name}/${parentAuthor}/${parentPermlink}`; // different draftId for each user acount - - const meta = await extractMetadata({ body: fields.body, fetchRatios: true, @@ -859,10 +862,9 @@ class EditorContainer extends Component { isPostSending: true, }); - //build speak video body + // build speak video body fields.body = speakContentBuilder.build(fields.body); - const { tags, body, title } = fields; const { markdownBody: oldBody, @@ -890,7 +892,6 @@ class EditorContainer extends Component { jsonMeta = makeJsonMetadata(meta, tags); } - await postContent( currentAccount, pinCode, diff --git a/src/utils/editor.ts b/src/utils/editor.ts index ce194b4cc..cf3e10137 100644 --- a/src/utils/editor.ts +++ b/src/utils/editor.ts @@ -274,7 +274,7 @@ export const extractMetadata = async ({ ); } - //insert three speak meta + // insert three speak meta if (videoPublishMeta) { const videoMetadata = videoPublishMeta.rawData; out.video = { From cd7db57ed790754d3a242275c0dd84115f0d7871 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 16 Nov 2023 18:21:19 +0500 Subject: [PATCH 065/111] removed test alert --- .../uploadsGalleryModal/children/uploadsGalleryContent.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx index 8b44764d0..3903af984 100644 --- a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx +++ b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx @@ -129,7 +129,7 @@ const UploadsGalleryContent = ({ const vidBeneficiaries = JSON.parse(item.speakData.beneficiaries || '[]'); const beneficiaries = [...DEFAULT_SPEAK_BENEFICIARIES, ...vidBeneficiaries]; const _draftId = draftId || TEMP_BENEFICIARIES_ID; - Alert.alert(_draftId, JSON.stringify(beneficiaries)); + dispatch(setBeneficiaries(_draftId, beneficiaries)); } } From e453deaf869ce85a48ada8d791267d5c7deb27dd Mon Sep 17 00:00:00 2001 From: noumantahir Date: Thu, 16 Nov 2023 18:45:24 +0500 Subject: [PATCH 066/111] hide unpublished videos for edits and replies --- .../children/uploadsGalleryContent.tsx | 12 ++++++++++++ src/redux/actions/editorActions.ts | 7 ++++++- src/redux/constants/constants.js | 1 + src/redux/reducers/editorReducer.ts | 9 ++++++++- src/screens/editor/container/editorContainer.tsx | 7 +++++-- 5 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx index 3903af984..96e42637b 100644 --- a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx +++ b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx @@ -24,6 +24,7 @@ import { setBeneficiaries } from '../../../redux/actions/editorActions'; import { TEMP_BENEFICIARIES_ID } from '../../../redux/constants/constants'; import { DEFAULT_SPEAK_BENEFICIARIES } from '../../../providers/speak/constants'; import { showActionModal } from '../../../redux/actions/uiAction'; +import { useAppSelector } from '../../../hooks'; type Props = { draftId?: string; @@ -49,6 +50,8 @@ const UploadsGalleryContent = ({ const deleteMediaMutation = editorQueries.useMediaDeleteMutation(); + const allowSpkPublishing = useAppSelector(state => state.editor.allowSpkPublishing); + const [deleteIds, setDeleteIds] = useState([]); const [isDeleteMode, setIsDeleteMode] = useState(false); const [isExpandedMode, setIsExpandedMode] = useState(false); @@ -101,6 +104,15 @@ const UploadsGalleryContent = ({ // render list item for snippet and handle actions; const _renderItem = ({ item, index }: { item: MediaItem; index: number }) => { + + //avoid rendering unpublihsed videos in allow publishing state is false + if( + !allowSpkPublishing && + item.speakData && + item.speakData.status !== ThreeSpeakStatus.PUBLISHED ){ + return null; + } + const _onPress = () => { if (isDeleteMode) { const idIndex = deleteIds.indexOf(item._id); diff --git a/src/redux/actions/editorActions.ts b/src/redux/actions/editorActions.ts index 7d895baeb..cf92c6462 100644 --- a/src/redux/actions/editorActions.ts +++ b/src/redux/actions/editorActions.ts @@ -1,4 +1,4 @@ -import { SET_BENEFICIARIES, REMOVE_BENEFICIARIES } from '../constants/constants'; +import { SET_BENEFICIARIES, REMOVE_BENEFICIARIES, SET_ALLOW_SPK_PUBLISHING } from '../constants/constants'; import { Beneficiary } from '../reducers/editorReducer'; export const setBeneficiaries = (draftId: string, benficiaries: Beneficiary[]) => ({ @@ -15,3 +15,8 @@ export const removeBeneficiaries = (draftId: string) => ({ }, type: REMOVE_BENEFICIARIES, }); + +export const setAllowSpkPublishing = (allowSpkPublishing:boolean) => ({ + payload:allowSpkPublishing, + type:SET_ALLOW_SPK_PUBLISHING +}) diff --git a/src/redux/constants/constants.js b/src/redux/constants/constants.js index 03b0f36e1..8f44a3efd 100644 --- a/src/redux/constants/constants.js +++ b/src/redux/constants/constants.js @@ -117,6 +117,7 @@ export const SET_OWN_PROFILE_TABS = 'SET_OWN_PROFILE_TABS'; export const SET_BENEFICIARIES = 'SET_BENEFICIARIES'; export const REMOVE_BENEFICIARIES = 'REMOVE_BENEFICIARIES'; export const TEMP_BENEFICIARIES_ID = 'temp-beneficiaries'; +export const SET_ALLOW_SPK_PUBLISHING = 'SET_ALLOW_SPK_PUBLISHING' // CACHE export const PURGE_EXPIRED_CACHE = 'PURGE_EXPIRED_CACHE'; diff --git a/src/redux/reducers/editorReducer.ts b/src/redux/reducers/editorReducer.ts index 07be23fb4..25a6bae08 100644 --- a/src/redux/reducers/editorReducer.ts +++ b/src/redux/reducers/editorReducer.ts @@ -1,4 +1,4 @@ -import { REMOVE_BENEFICIARIES, SET_BENEFICIARIES } from '../constants/constants'; +import { REMOVE_BENEFICIARIES, SET_BENEFICIARIES, SET_ALLOW_SPK_PUBLISHING } from '../constants/constants'; export interface Beneficiary { account: string; @@ -11,10 +11,12 @@ interface State { beneficiariesMap: { [key: string]: Beneficiary[]; }; + allowSpkPublishing: boolean; } const initialState: State = { beneficiariesMap: {}, + allowSpkPublishing: false }; const editorReducer = (state = initialState, action) => { @@ -30,6 +32,11 @@ const editorReducer = (state = initialState, action) => { return { ...state, // spread operator in requried here, otherwise persist do not register change }; + case SET_ALLOW_SPK_PUBLISHING: + return { + ...state, + allowSpkPublishing:payload + } default: return state; } diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 130276963..3360c60d0 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -39,7 +39,7 @@ import { // Component import EditorScreen from '../screen/editorScreen'; -import { removeBeneficiaries, setBeneficiaries } from '../../../redux/actions/editorActions'; +import { removeBeneficiaries, setAllowSpkPublishing, setBeneficiaries } from '../../../redux/actions/editorActions'; import { DEFAULT_USER_DRAFT_ID, TEMP_BENEFICIARIES_ID } from '../../../redux/constants/constants'; import { deleteDraftCacheEntry, @@ -102,7 +102,7 @@ class EditorContainer extends Component { // Component Life Cycle Functions componentDidMount() { this._isMounted = true; - const { currentAccount, route, queryClient } = this.props; + const { currentAccount, route, queryClient, dispatch } = this.props; const username = currentAccount && currentAccount.name ? currentAccount.name : ''; let isReply; let draftId; @@ -198,6 +198,9 @@ class EditorContainer extends Component { this._requestKeyboardFocus(); this._appStateSub = AppState.addEventListener('change', this._handleAppStateChange); + + //dispatch spk publishing status + dispatch(setAllowSpkPublishing(!isReply && !isEdit)) } componentDidUpdate(prevProps: Readonly, prevState: Readonly): void { From f4de28cb31c53364abf379ccad0a1a8635d368ab Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 17 Nov 2023 14:29:49 +0500 Subject: [PATCH 067/111] added barebone speak uploader modal view --- .../children/speakUploaderModal.tsx | 106 ++++++++++++++++++ .../container/uploadsGalleryModal.tsx | 68 +++++++---- .../styles/speakUploaderModal.styles.ts | 61 ++++++++++ 3 files changed, 215 insertions(+), 20 deletions(-) create mode 100644 src/components/uploadsGalleryModal/children/speakUploaderModal.tsx create mode 100644 src/components/uploadsGalleryModal/styles/speakUploaderModal.styles.ts diff --git a/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx b/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx new file mode 100644 index 000000000..8f28a3df5 --- /dev/null +++ b/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx @@ -0,0 +1,106 @@ +import React, { forwardRef, useImperativeHandle, useState } from "react"; +import { useRef } from "react"; +import { View, Text, TouchableOpacity, Image, TextInput } from "react-native"; +import ActionSheet from "react-native-actions-sheet"; +import EStyleSheet from "react-native-extended-stylesheet"; +import styles from "../styles/speakUploaderModal.styles"; +import { MainButton } from "../../mainButton"; + + +export const SpeakUploaderModal = forwardRef(({ }, ref) => { + + const sheetModalRef = useRef(); + + const [image1, setImage1] = useState(null); + const [image2, setImage2] = useState(null); + const [title, setTitle] = useState(''); + const [isUploading, setIsUploading] = useState(false); + + useImperativeHandle(ref, () => ({ + showUploader: () => { + if (sheetModalRef.current) { + sheetModalRef.current.setModalVisible(true); + } + } + })) + + const _onClose = () => { + + } + + const _renderProgressContent = () => { + + } + + const _renderFormContent = () => { + + + // Function to handle image upload + const handleImageUpload = (imageNumber) => { + // You can implement your logic for image upload here + // For example, using ImagePicker or any other method + // This example simply sets a placeholder image + + //Upload video and thumbnail if selected + }; + + return ( + + + + Selection + + + + + Title + setTitle(text)} + value={title} + /> + + + + Select Thumbnail + handleImageUpload(2)}> + + + + + {/* Handle upload */ }} + + text="START UPLOAD" + isLoading={isUploading} + /> + + + ); + }; + + + + return ( + + {_renderFormContent()} + + ); +}) \ No newline at end of file diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 53c3b8336..87d179495 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -8,7 +8,7 @@ import React, { } from 'react'; import { useIntl } from 'react-intl'; import { Alert, AlertButton } from 'react-native'; -import ImagePicker, { Image } from 'react-native-image-crop-picker'; +import ImagePicker, { Image, Options, Video } from 'react-native-image-crop-picker'; import RNHeicConverter from 'react-native-heic-converter'; import { openSettings } from 'react-native-permissions'; import bugsnapInstance from '../../../config/bugsnag'; @@ -25,6 +25,7 @@ import showLoginAlert from '../../../utils/showLoginAlert'; import { editorQueries, speakQueries } from '../../../providers/queries'; import { showActionModal } from '../../../redux/actions/uiAction'; import { MediaItem } from '../../../providers/ecency/ecency.types'; +import { SpeakUploaderModal } from '../children/speakUploaderModal'; export interface UploadsGalleryModalRef { showModal: () => void; @@ -85,6 +86,7 @@ export const UploadsGalleryModal = forwardRef( const mediaUploadMutation = editorQueries.useMediaUploadMutation(); const pendingInserts = useRef([]); + const speakUploaderRef = useRef(); const [showModal, setShowModal] = useState(false); const [isAddingToUploads, setIsAddingToUploads] = useState(false); @@ -171,17 +173,28 @@ export const UploadsGalleryModal = forwardRef( }, [postBody, showModal, mode]); const _handleOpenImagePicker = (addToUploads?: boolean) => { - ImagePicker.openPicker({ + + const _options: Options = mode === Modes.MODE_IMAGE ? { includeBase64: true, multiple: allowMultiple || true, mediaType: 'photo', smartAlbums: ['UserLibrary', 'Favorites', 'PhotoStream', 'Panoramas', 'Bursts'], - }) - .then((images) => { - if (images && !Array.isArray(images)) { - images = [images]; + } : { + mediaType: 'video', + smartAlbums: ['UserLibrary', 'Favorites', 'Videos'], + } + + if(Modes.MODE_VIDEO){ + _handleVideoSelection(); + return; + } + + ImagePicker.openPicker(_options) + .then((items) => { + if (items && !Array.isArray(items)) { + items = [items]; } - _handleMediaOnSelected(images, !addToUploads); + _handleMediaOnSelected(items, !addToUploads); }) .catch((e) => { _handleMediaOnSelectFailure(e); @@ -344,6 +357,13 @@ export const UploadsGalleryModal = forwardRef( } }; + + const _handleVideoSelection = (video: Video) => { + //show video upload modal, + //allow thumbnail selection and uplaods + speakUploaderRef.current.showUploader(); + } + const _handleMediaOnSelectFailure = (error) => { let title = intl.formatMessage({ id: 'alert.something_wrong' }); let body = error.message || JSON.stringify(error); @@ -419,20 +439,28 @@ export const UploadsGalleryModal = forwardRef( const data = mediaUploadsQuery.data.slice(); + if (isPreviewActive) { + return null; + } + return ( - !isPreviewActive && - showModal && ( - + {showModal && ( + + )} + - ) - ); + + ) }, ); diff --git a/src/components/uploadsGalleryModal/styles/speakUploaderModal.styles.ts b/src/components/uploadsGalleryModal/styles/speakUploaderModal.styles.ts new file mode 100644 index 000000000..9d8895dbb --- /dev/null +++ b/src/components/uploadsGalleryModal/styles/speakUploaderModal.styles.ts @@ -0,0 +1,61 @@ +import EStyleSheet from "react-native-extended-stylesheet"; + +export default EStyleSheet.create({ + modalStyle: { + backgroundColor: '$primaryBackgroundColor', + margin: 0, + paddingTop: 32, + paddingBottom: 8, + }, + + sheetContent: { + backgroundColor: '$primaryBackgroundColor', + position: 'absolute', + bottom: 0, + left: 0, + right: 0, + zIndex: 999, + }, + contentContainer: { + padding: 16, + paddingBottom:40 + }, + imageContainer: { + marginBottom: 20, + }, + thumbnail: { + marginTop: 10, + width: 177, + height: 100, + resizeMode: 'cover', + borderRadius: 8, + backgroundColor:"$primaryLightBackground" + }, + label:{ + color: '$primaryDarkGray', + fontSize: 14, + fontWeight: 'bold', + flexGrow: 1, + textAlign: 'left', + }, + titleBox: { + marginBottom: 20, + }, + titleInput: { + borderWidth: 1, + borderColor: '#ccc', + borderRadius: 5, + padding: 8, + width: '80%', + marginTop: 10, + color: '$primaryDarkGray', + }, + uploadButton: { + marginBottom: 24, paddingHorizontal:16, alignSelf: 'center', alignItems:'center' + }, + buttonText: { + color: 'white', + fontSize: 16, + fontWeight: 'bold', + }, +}) From 9a2f4f7c07721797829b1429b56b4a57dac1f1aa Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 17 Nov 2023 14:30:46 +0500 Subject: [PATCH 068/111] lint --- .../children/speakUploaderModal.tsx | 61 +++------ .../children/uploadsGalleryContent.tsx | 14 +- .../container/uploadsGalleryModal.tsx | 37 +++--- .../styles/speakUploaderModal.styles.ts | 121 +++++++++--------- src/redux/actions/editorActions.ts | 14 +- src/redux/constants/constants.js | 2 +- src/redux/reducers/editorReducer.ts | 12 +- .../editor/container/editorContainer.tsx | 10 +- 8 files changed, 133 insertions(+), 138 deletions(-) diff --git a/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx b/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx index 8f28a3df5..530f05a80 100644 --- a/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx +++ b/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx @@ -1,14 +1,12 @@ -import React, { forwardRef, useImperativeHandle, useState } from "react"; -import { useRef } from "react"; -import { View, Text, TouchableOpacity, Image, TextInput } from "react-native"; -import ActionSheet from "react-native-actions-sheet"; -import EStyleSheet from "react-native-extended-stylesheet"; -import styles from "../styles/speakUploaderModal.styles"; -import { MainButton } from "../../mainButton"; - - -export const SpeakUploaderModal = forwardRef(({ }, ref) => { +import React, { forwardRef, useImperativeHandle, useState } from 'react'; +import { useRef } from 'react'; +import { View, Text, TouchableOpacity, Image, TextInput } from 'react-native'; +import ActionSheet from 'react-native-actions-sheet'; +import EStyleSheet from 'react-native-extended-stylesheet'; +import styles from '../styles/speakUploaderModal.styles'; +import { MainButton } from '../../mainButton'; +export const SpeakUploaderModal = forwardRef(({}, ref) => { const sheetModalRef = useRef(); const [image1, setImage1] = useState(null); @@ -21,39 +19,27 @@ export const SpeakUploaderModal = forwardRef(({ }, ref) => { if (sheetModalRef.current) { sheetModalRef.current.setModalVisible(true); } - } - })) + }, + })); - const _onClose = () => { + const _onClose = () => {}; - } - - const _renderProgressContent = () => { - - } + const _renderProgressContent = () => {}; const _renderFormContent = () => { - - // Function to handle image upload const handleImageUpload = (imageNumber) => { // You can implement your logic for image upload here // For example, using ImagePicker or any other method // This example simply sets a placeholder image - - //Upload video and thumbnail if selected + // Upload video and thumbnail if selected }; return ( - Selection - + @@ -68,29 +54,24 @@ export const SpeakUploaderModal = forwardRef(({ }, ref) => { - Select Thumbnail + Select Thumbnail handleImageUpload(2)}> - + {/* Handle upload */ }} - + onPress={() => { + /* Handle upload */ + }} text="START UPLOAD" - isLoading={isUploading} + isLoading={isUploading} /> - ); }; - - return ( { {_renderFormContent()} ); -}) \ No newline at end of file +}); diff --git a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx index 96e42637b..b0730cea6 100644 --- a/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx +++ b/src/components/uploadsGalleryModal/children/uploadsGalleryContent.tsx @@ -50,7 +50,7 @@ const UploadsGalleryContent = ({ const deleteMediaMutation = editorQueries.useMediaDeleteMutation(); - const allowSpkPublishing = useAppSelector(state => state.editor.allowSpkPublishing); + const allowSpkPublishing = useAppSelector((state) => state.editor.allowSpkPublishing); const [deleteIds, setDeleteIds] = useState([]); const [isDeleteMode, setIsDeleteMode] = useState(false); @@ -104,12 +104,12 @@ const UploadsGalleryContent = ({ // render list item for snippet and handle actions; const _renderItem = ({ item, index }: { item: MediaItem; index: number }) => { - - //avoid rendering unpublihsed videos in allow publishing state is false - if( + // avoid rendering unpublihsed videos in allow publishing state is false + if ( !allowSpkPublishing && - item.speakData && - item.speakData.status !== ThreeSpeakStatus.PUBLISHED ){ + item.speakData && + item.speakData.status !== ThreeSpeakStatus.PUBLISHED + ) { return null; } @@ -141,7 +141,7 @@ const UploadsGalleryContent = ({ const vidBeneficiaries = JSON.parse(item.speakData.beneficiaries || '[]'); const beneficiaries = [...DEFAULT_SPEAK_BENEFICIARIES, ...vidBeneficiaries]; const _draftId = draftId || TEMP_BENEFICIARIES_ID; - + dispatch(setBeneficiaries(_draftId, beneficiaries)); } } diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 87d179495..14da00cbd 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -173,18 +173,20 @@ export const UploadsGalleryModal = forwardRef( }, [postBody, showModal, mode]); const _handleOpenImagePicker = (addToUploads?: boolean) => { + const _options: Options = + mode === Modes.MODE_IMAGE + ? { + includeBase64: true, + multiple: allowMultiple || true, + mediaType: 'photo', + smartAlbums: ['UserLibrary', 'Favorites', 'PhotoStream', 'Panoramas', 'Bursts'], + } + : { + mediaType: 'video', + smartAlbums: ['UserLibrary', 'Favorites', 'Videos'], + }; - const _options: Options = mode === Modes.MODE_IMAGE ? { - includeBase64: true, - multiple: allowMultiple || true, - mediaType: 'photo', - smartAlbums: ['UserLibrary', 'Favorites', 'PhotoStream', 'Panoramas', 'Bursts'], - } : { - mediaType: 'video', - smartAlbums: ['UserLibrary', 'Favorites', 'Videos'], - } - - if(Modes.MODE_VIDEO){ + if (Modes.MODE_VIDEO) { _handleVideoSelection(); return; } @@ -357,12 +359,11 @@ export const UploadsGalleryModal = forwardRef( } }; - const _handleVideoSelection = (video: Video) => { - //show video upload modal, - //allow thumbnail selection and uplaods + // show video upload modal, + // allow thumbnail selection and uplaods speakUploaderRef.current.showUploader(); - } + }; const _handleMediaOnSelectFailure = (error) => { let title = intl.formatMessage({ id: 'alert.something_wrong' }); @@ -457,10 +458,8 @@ export const UploadsGalleryModal = forwardRef( handleOpenGallery={_handleOpenImagePicker} /> )} - + - ) + ); }, ); diff --git a/src/components/uploadsGalleryModal/styles/speakUploaderModal.styles.ts b/src/components/uploadsGalleryModal/styles/speakUploaderModal.styles.ts index 9d8895dbb..01ad24225 100644 --- a/src/components/uploadsGalleryModal/styles/speakUploaderModal.styles.ts +++ b/src/components/uploadsGalleryModal/styles/speakUploaderModal.styles.ts @@ -1,61 +1,64 @@ -import EStyleSheet from "react-native-extended-stylesheet"; +import EStyleSheet from 'react-native-extended-stylesheet'; export default EStyleSheet.create({ - modalStyle: { - backgroundColor: '$primaryBackgroundColor', - margin: 0, - paddingTop: 32, - paddingBottom: 8, - }, - - sheetContent: { - backgroundColor: '$primaryBackgroundColor', - position: 'absolute', - bottom: 0, - left: 0, - right: 0, - zIndex: 999, - }, - contentContainer: { - padding: 16, - paddingBottom:40 - }, - imageContainer: { - marginBottom: 20, - }, - thumbnail: { - marginTop: 10, - width: 177, - height: 100, - resizeMode: 'cover', - borderRadius: 8, - backgroundColor:"$primaryLightBackground" - }, - label:{ - color: '$primaryDarkGray', - fontSize: 14, - fontWeight: 'bold', - flexGrow: 1, - textAlign: 'left', - }, - titleBox: { - marginBottom: 20, - }, - titleInput: { - borderWidth: 1, - borderColor: '#ccc', - borderRadius: 5, - padding: 8, - width: '80%', - marginTop: 10, - color: '$primaryDarkGray', - }, - uploadButton: { - marginBottom: 24, paddingHorizontal:16, alignSelf: 'center', alignItems:'center' - }, - buttonText: { - color: 'white', - fontSize: 16, - fontWeight: 'bold', - }, -}) + modalStyle: { + backgroundColor: '$primaryBackgroundColor', + margin: 0, + paddingTop: 32, + paddingBottom: 8, + }, + + sheetContent: { + backgroundColor: '$primaryBackgroundColor', + position: 'absolute', + bottom: 0, + left: 0, + right: 0, + zIndex: 999, + }, + contentContainer: { + padding: 16, + paddingBottom: 40, + }, + imageContainer: { + marginBottom: 20, + }, + thumbnail: { + marginTop: 10, + width: 177, + height: 100, + resizeMode: 'cover', + borderRadius: 8, + backgroundColor: '$primaryLightBackground', + }, + label: { + color: '$primaryDarkGray', + fontSize: 14, + fontWeight: 'bold', + flexGrow: 1, + textAlign: 'left', + }, + titleBox: { + marginBottom: 20, + }, + titleInput: { + borderWidth: 1, + borderColor: '#ccc', + borderRadius: 5, + padding: 8, + width: '80%', + marginTop: 10, + color: '$primaryDarkGray', + }, + uploadButton: { + marginBottom: 24, + paddingHorizontal: 16, + alignSelf: 'center', + alignItems: 'center', + }, + buttonText: { + color: 'white', + fontSize: 16, + fontWeight: 'bold', + }, +}); diff --git a/src/redux/actions/editorActions.ts b/src/redux/actions/editorActions.ts index cf92c6462..ead6c1853 100644 --- a/src/redux/actions/editorActions.ts +++ b/src/redux/actions/editorActions.ts @@ -1,4 +1,8 @@ -import { SET_BENEFICIARIES, REMOVE_BENEFICIARIES, SET_ALLOW_SPK_PUBLISHING } from '../constants/constants'; +import { + SET_BENEFICIARIES, + REMOVE_BENEFICIARIES, + SET_ALLOW_SPK_PUBLISHING, +} from '../constants/constants'; import { Beneficiary } from '../reducers/editorReducer'; export const setBeneficiaries = (draftId: string, benficiaries: Beneficiary[]) => ({ @@ -16,7 +20,7 @@ export const removeBeneficiaries = (draftId: string) => ({ type: REMOVE_BENEFICIARIES, }); -export const setAllowSpkPublishing = (allowSpkPublishing:boolean) => ({ - payload:allowSpkPublishing, - type:SET_ALLOW_SPK_PUBLISHING -}) +export const setAllowSpkPublishing = (allowSpkPublishing: boolean) => ({ + payload: allowSpkPublishing, + type: SET_ALLOW_SPK_PUBLISHING, +}); diff --git a/src/redux/constants/constants.js b/src/redux/constants/constants.js index 8f44a3efd..99ed13f09 100644 --- a/src/redux/constants/constants.js +++ b/src/redux/constants/constants.js @@ -117,7 +117,7 @@ export const SET_OWN_PROFILE_TABS = 'SET_OWN_PROFILE_TABS'; export const SET_BENEFICIARIES = 'SET_BENEFICIARIES'; export const REMOVE_BENEFICIARIES = 'REMOVE_BENEFICIARIES'; export const TEMP_BENEFICIARIES_ID = 'temp-beneficiaries'; -export const SET_ALLOW_SPK_PUBLISHING = 'SET_ALLOW_SPK_PUBLISHING' +export const SET_ALLOW_SPK_PUBLISHING = 'SET_ALLOW_SPK_PUBLISHING'; // CACHE export const PURGE_EXPIRED_CACHE = 'PURGE_EXPIRED_CACHE'; diff --git a/src/redux/reducers/editorReducer.ts b/src/redux/reducers/editorReducer.ts index 25a6bae08..8031f0717 100644 --- a/src/redux/reducers/editorReducer.ts +++ b/src/redux/reducers/editorReducer.ts @@ -1,4 +1,8 @@ -import { REMOVE_BENEFICIARIES, SET_BENEFICIARIES, SET_ALLOW_SPK_PUBLISHING } from '../constants/constants'; +import { + REMOVE_BENEFICIARIES, + SET_BENEFICIARIES, + SET_ALLOW_SPK_PUBLISHING, +} from '../constants/constants'; export interface Beneficiary { account: string; @@ -16,7 +20,7 @@ interface State { const initialState: State = { beneficiariesMap: {}, - allowSpkPublishing: false + allowSpkPublishing: false, }; const editorReducer = (state = initialState, action) => { @@ -35,8 +39,8 @@ const editorReducer = (state = initialState, action) => { case SET_ALLOW_SPK_PUBLISHING: return { ...state, - allowSpkPublishing:payload - } + allowSpkPublishing: payload, + }; default: return state; } diff --git a/src/screens/editor/container/editorContainer.tsx b/src/screens/editor/container/editorContainer.tsx index 3360c60d0..2e2bc0245 100644 --- a/src/screens/editor/container/editorContainer.tsx +++ b/src/screens/editor/container/editorContainer.tsx @@ -39,7 +39,11 @@ import { // Component import EditorScreen from '../screen/editorScreen'; -import { removeBeneficiaries, setAllowSpkPublishing, setBeneficiaries } from '../../../redux/actions/editorActions'; +import { + removeBeneficiaries, + setAllowSpkPublishing, + setBeneficiaries, +} from '../../../redux/actions/editorActions'; import { DEFAULT_USER_DRAFT_ID, TEMP_BENEFICIARIES_ID } from '../../../redux/constants/constants'; import { deleteDraftCacheEntry, @@ -199,8 +203,8 @@ class EditorContainer extends Component { this._appStateSub = AppState.addEventListener('change', this._handleAppStateChange); - //dispatch spk publishing status - dispatch(setAllowSpkPublishing(!isReply && !isEdit)) + // dispatch spk publishing status + dispatch(setAllowSpkPublishing(!isReply && !isEdit)); } componentDidUpdate(prevProps: Readonly, prevState: Readonly): void { From 61271e25897ad867709a116d223855bf251f4593 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 17 Nov 2023 16:23:00 +0500 Subject: [PATCH 069/111] first video selection to upload simple post --- .../children/speakUploaderModal.tsx | 33 ++++++++-- .../container/uploadsGalleryModal.tsx | 60 +++++++++++-------- src/providers/speak/speak.ts | 5 +- 3 files changed, 67 insertions(+), 31 deletions(-) diff --git a/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx b/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx index 530f05a80..522a460e7 100644 --- a/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx +++ b/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx @@ -5,6 +5,8 @@ import ActionSheet from 'react-native-actions-sheet'; import EStyleSheet from 'react-native-extended-stylesheet'; import styles from '../styles/speakUploaderModal.styles'; import { MainButton } from '../../mainButton'; +import { Video } from 'react-native-image-crop-picker'; +import { uploadVideo } from '../../../providers/speak/speak'; export const SpeakUploaderModal = forwardRef(({}, ref) => { const sheetModalRef = useRef(); @@ -14,16 +16,39 @@ export const SpeakUploaderModal = forwardRef(({}, ref) => { const [title, setTitle] = useState(''); const [isUploading, setIsUploading] = useState(false); + const [selectedVido, setSelectedVideo] = useState(null); + useImperativeHandle(ref, () => ({ - showUploader: () => { + showUploader: (_video:Video) => { if (sheetModalRef.current) { + setSelectedVideo(_video); sheetModalRef.current.setModalVisible(true); } }, })); + const _startUpload = async () => { + + if(!selectedVido){ + return + } + + try{ + const response = await uploadVideo(selectedVido, (progress) => { + console.log("Upload progress", progress) + }) + + console.log("uploda video response", response); + } catch(err){ + console.warn("Video upload failed", err) + } + + } + + const _onClose = () => {}; + const _renderProgressContent = () => {}; const _renderFormContent = () => { @@ -39,7 +64,7 @@ export const SpeakUploaderModal = forwardRef(({}, ref) => { Selection - + @@ -62,9 +87,7 @@ export const SpeakUploaderModal = forwardRef(({}, ref) => { { - /* Handle upload */ - }} + onPress={_startUpload} text="START UPLOAD" isLoading={isUploading} /> diff --git a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx index 14da00cbd..a27802f58 100644 --- a/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx +++ b/src/components/uploadsGalleryModal/container/uploadsGalleryModal.tsx @@ -173,30 +173,30 @@ export const UploadsGalleryModal = forwardRef( }, [postBody, showModal, mode]); const _handleOpenImagePicker = (addToUploads?: boolean) => { - const _options: Options = - mode === Modes.MODE_IMAGE - ? { - includeBase64: true, - multiple: allowMultiple || true, - mediaType: 'photo', - smartAlbums: ['UserLibrary', 'Favorites', 'PhotoStream', 'Panoramas', 'Bursts'], - } - : { - mediaType: 'video', - smartAlbums: ['UserLibrary', 'Favorites', 'Videos'], - }; + const _vidMode = mode === Modes.MODE_VIDEO + const _options: Options = _vidMode ? + { + mediaType: 'video', + smartAlbums: ['UserLibrary', 'Favorites', 'Videos'], + } : { + includeBase64: true, + multiple: allowMultiple || true, + mediaType: 'photo', + smartAlbums: ['UserLibrary', 'Favorites', 'PhotoStream', 'Panoramas', 'Bursts'], + } - if (Modes.MODE_VIDEO) { - _handleVideoSelection(); - return; - } ImagePicker.openPicker(_options) .then((items) => { if (items && !Array.isArray(items)) { items = [items]; } - _handleMediaOnSelected(items, !addToUploads); + if (_vidMode) { + _handleVideoSelection(items[0]); + } else { + _handleMediaOnSelected(items, !addToUploads); + } + }) .catch((e) => { _handleMediaOnSelectFailure(e); @@ -204,12 +204,24 @@ export const UploadsGalleryModal = forwardRef( }; const _handleOpenCamera = () => { - ImagePicker.openCamera({ - includeBase64: true, - mediaType: 'photo', - }) - .then((image) => { - _handleMediaOnSelected([image], true); + + const _vidMode = mode === Modes.MODE_VIDEO + const _options: Options = _vidMode ? + { + mediaType: 'video', + } : { + includeBase64: true, + mediaType: 'photo', + }; + + ImagePicker.openCamera(_options) + .then((media) => { + if(_vidMode){ + _handleVideoSelection(media); + }else { + _handleMediaOnSelected([media], true); + } + }) .catch((e) => { _handleMediaOnSelectFailure(e); @@ -362,7 +374,7 @@ export const UploadsGalleryModal = forwardRef( const _handleVideoSelection = (video: Video) => { // show video upload modal, // allow thumbnail selection and uplaods - speakUploaderRef.current.showUploader(); + speakUploaderRef.current.showUploader(video); }; const _handleMediaOnSelectFailure = (error) => { diff --git a/src/providers/speak/speak.ts b/src/providers/speak/speak.ts index 1c47a9c66..b4ac4156e 100644 --- a/src/providers/speak/speak.ts +++ b/src/providers/speak/speak.ts @@ -5,6 +5,7 @@ import { ThreeSpeakVideo } from './speak.types'; import { decryptKey } from '../../utils/crypto'; import { convertVideoUpload } from './converters'; import { BASE_URL_SPEAK_STUDIO, PATH_API, PATH_LOGIN, PATH_MOBILE } from './constants'; +import { Video } from 'react-native-image-crop-picker'; const tusEndPoint = 'https://uploads.3speak.tv/files/'; @@ -144,12 +145,12 @@ export const markAsPublished = async (currentAccount: any, pinHash: string, vide }); }; -export const uploadVideo = async (media, onUploadProgress) => { +export const uploadVideo = async (media:Video, onUploadProgress) => { try { const file = { uri: media.path, type: media.mime, - name: media.filename || `img_${Math.random()}.mp4`, + name: media.filename || `vid_${Math.random()}.mp4`, size: media.size, }; From 8272fc24dbfcdfbac2ecaf2ea1734af3fafb5c21 Mon Sep 17 00:00:00 2001 From: noumantahir Date: Fri, 17 Nov 2023 17:37:09 +0500 Subject: [PATCH 070/111] using tus client to upload video and thumb --- ios/Ecency.xcodeproj/project.pbxproj | 472 +++++++++--------- ios/Podfile.lock | 10 + package.json | 3 +- patches/react-native-tus-client+1.1.0.patch | 11 + .../children/speakUploaderModal.tsx | 79 +-- .../container/uploadsGalleryModal.tsx | 48 +- src/providers/speak/speak.ts | 111 ++-- yarn.lock | 5 + 8 files changed, 374 insertions(+), 365 deletions(-) create mode 100644 patches/react-native-tus-client+1.1.0.patch diff --git a/ios/Ecency.xcodeproj/project.pbxproj b/ios/Ecency.xcodeproj/project.pbxproj index 4235d0532..63a6187c1 100644 --- a/ios/Ecency.xcodeproj/project.pbxproj +++ b/ios/Ecency.xcodeproj/project.pbxproj @@ -9,7 +9,6 @@ /* Begin PBXBuildFile section */ 00E356F31AD99517003FC87E /* EcencyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* EcencyTests.m */; }; 021526F0AF8A45FCB60C9C56 /* Roboto-medium.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 7900A87FFF214846B5FE0430 /* Roboto-medium.ttf */; }; - 04D1BA15BBCF7F2B9E3612BF /* libPods-Ecency-EcencyTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 0FDDF70C668E24276B7F7D91 /* libPods-Ecency-EcencyTests.a */; }; 0516470B24D2C513005DE9C5 /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0516470A24D2C513005DE9C5 /* ShareViewController.swift */; }; 0516470E24D2C513005DE9C5 /* MainInterface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 0516470C24D2C513005DE9C5 /* MainInterface.storyboard */; }; 0516471224D2C513005DE9C5 /* eshare.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 0516470824D2C513005DE9C5 /* eshare.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; @@ -29,15 +28,16 @@ 2D02E4BF1E0B4AB3006451C7 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; }; 2DCD954D1E0B4F2C00145EB5 /* EcencyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* EcencyTests.m */; }; 2E340255E74B48D8AF5B650C /* Sansation_Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 5ADE4B4B75DF437495E202D4 /* Sansation_Regular.ttf */; }; - 31856ADD6C0311522CA1DFA7 /* libPods-Ecency.a in Frameworks */ = {isa = PBXBuildFile; fileRef = FA5F73032F66B1EBAA61B851 /* libPods-Ecency.a */; }; - 3ABD43432246ECAC42DCEE31 /* libPods-ImageNotifi.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 573C027160DB8491D45BFEA8 /* libPods-ImageNotifi.a */; }; + 559F6876CF90046F127B01A7 /* libPods-ImageNotifi.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 319533F3C37053AA08129D61 /* libPods-ImageNotifi.a */; }; 58F9BCC624793C61004F0790 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 58F9BCC224793C61004F0790 /* GoogleService-Info.plist */; }; 58F9BCC724793C61004F0790 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 58F9BCC224793C61004F0790 /* GoogleService-Info.plist */; }; 58F9BCC824793C61004F0790 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 58F9BCC224793C61004F0790 /* GoogleService-Info.plist */; }; + 591DCA36C99F9CEF3DDF91F0 /* libPods-Ecency.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1139E19235945FF6A16519D6 /* libPods-Ecency.a */; }; 7C8D083700274C80BADEB3D6 /* Sansation_Bold.ttf in Resources */ = {isa = PBXBuildFile; fileRef = F1D77AE9F7B24CF19834052B /* Sansation_Bold.ttf */; }; 89D99F65314A416290F8D921 /* Roboto.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 64F2A611E6EF486C8D3FB82C /* Roboto.ttf */; }; 92082305364D41A4A673F950 /* RobotoMono-Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 5795D1B1C55E46FF96CC4AED /* RobotoMono-Regular.ttf */; }; A57EE8B63D4948F0A05218E3 /* rubicon-icon-font.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 65F56948860941D6BA55779F /* rubicon-icon-font.ttf */; }; + CAB37987FC01E2F3B078A1B0 /* libPods-Ecency-EcencyTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 0000A09C65210B9482224F67 /* libPods-Ecency-EcencyTests.a */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -94,6 +94,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 0000A09C65210B9482224F67 /* libPods-Ecency-EcencyTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Ecency-EcencyTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 000EE3558E824DA88770325D /* Octicons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Octicons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Octicons.ttf"; sourceTree = ""; }; 008F07F21AC5B25A0029DE68 /* main.jsbundle */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = main.jsbundle; sourceTree = ""; }; 00E356EE1AD99517003FC87E /* EcencyTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = EcencyTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -117,26 +118,24 @@ 06844A5429119F05002FCC34 /* BootSplash.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = BootSplash.storyboard; path = Ecency/BootSplash.storyboard; sourceTree = ""; }; 06F72CA2290B2159003392F3 /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = Ecency/AppDelegate.mm; sourceTree = ""; }; 06F72CA5290B2D7F003392F3 /* hermes.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = hermes.xcframework; path = "Pods/hermes-engine/destroot/Library/Frameworks/universal/hermes.xcframework"; sourceTree = ""; }; - 0AA04D912D96044AECF20A65 /* Pods-Ecency.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency.debug.xcconfig"; path = "Target Support Files/Pods-Ecency/Pods-Ecency.debug.xcconfig"; sourceTree = ""; }; - 0FDDF70C668E24276B7F7D91 /* libPods-Ecency-EcencyTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Ecency-EcencyTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 112758B0BBF9458381CE41FD /* FontAwesome.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = FontAwesome.ttf; path = "../node_modules/react-native-vector-icons/Fonts/FontAwesome.ttf"; sourceTree = ""; }; + 1139E19235945FF6A16519D6 /* libPods-Ecency.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Ecency.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 11CAB2F9B4B7425ABCAB4007 /* Foundation.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Foundation.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Foundation.ttf"; sourceTree = ""; }; 13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = Ecency/AppDelegate.h; sourceTree = ""; }; 13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = Ecency/Images.xcassets; sourceTree = ""; }; 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = Ecency/Info.plist; sourceTree = ""; }; 13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = Ecency/main.m; sourceTree = ""; }; 1CD0B89B258019B600A7D78E /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; - 1DFEA0938900B7C7E419498A /* Pods-Ecency-EcencyTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency-EcencyTests.release.xcconfig"; path = "Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests.release.xcconfig"; sourceTree = ""; }; 22F5F05A06E142C2B41A4D38 /* MaterialCommunityIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = MaterialCommunityIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf"; sourceTree = ""; }; 263FA8C0EF21473FAAAD3EDD /* MaterialIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = MaterialIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/MaterialIcons.ttf"; sourceTree = ""; }; 2D02E47B1E0B4A5D006451C7 /* Ecency-tvOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Ecency-tvOS.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 2D02E4901E0B4A5D006451C7 /* Ecency-tvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Ecency-tvOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 319533F3C37053AA08129D61 /* libPods-ImageNotifi.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-ImageNotifi.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 347F92D26DDA1405D2BF50E8 /* Pods-Ecency-EcencyTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency-EcencyTests.debug.xcconfig"; path = "Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests.debug.xcconfig"; sourceTree = ""; }; 34E88D888DD444F8B285363C /* SimpleLineIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = SimpleLineIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/SimpleLineIcons.ttf"; sourceTree = ""; }; - 404E707BFB0A754BDB18D41C /* Pods-Ecency-EcencyTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency-EcencyTests.debug.xcconfig"; path = "Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests.debug.xcconfig"; sourceTree = ""; }; 420ABF9795564845A0963C27 /* Feather.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Feather.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Feather.ttf"; sourceTree = ""; }; - 4CA976A51F8781F23710B585 /* Pods-ImageNotifi.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ImageNotifi.release.xcconfig"; path = "Target Support Files/Pods-ImageNotifi/Pods-ImageNotifi.release.xcconfig"; sourceTree = ""; }; 4EB466C53BAE4EDC904357B3 /* FontAwesome5_Solid.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = FontAwesome5_Solid.ttf; path = "../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Solid.ttf"; sourceTree = ""; }; - 573C027160DB8491D45BFEA8 /* libPods-ImageNotifi.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-ImageNotifi.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 56F7FFCAA3257C590A314DE7 /* Pods-Ecency.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency.debug.xcconfig"; path = "Target Support Files/Pods-Ecency/Pods-Ecency.debug.xcconfig"; sourceTree = ""; }; 5795D1B1C55E46FF96CC4AED /* RobotoMono-Regular.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = "RobotoMono-Regular.ttf"; path = "../src/assets/fonts/RobotoMono-Regular.ttf"; sourceTree = ""; }; 58190B3B23294814000EA0E1 /* StoreKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = StoreKit.framework; path = System/Library/Frameworks/StoreKit.framework; sourceTree = SDKROOT; }; 58190B3D23294823000EA0E1 /* Ecency.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; name = Ecency.entitlements; path = Ecency/Ecency.entitlements; sourceTree = ""; }; @@ -147,23 +146,24 @@ 58F6300F2350580B0017C953 /* libRealmJS.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; path = libRealmJS.a; sourceTree = BUILT_PRODUCTS_DIR; }; 58F9BCC224793C61004F0790 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; 5ADE4B4B75DF437495E202D4 /* Sansation_Regular.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Sansation_Regular.ttf; path = ../src/assets/fonts/Sansation_Regular.ttf; sourceTree = ""; }; + 64961AAC9D95CBD0493E4F11 /* Pods-ImageNotifi.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ImageNotifi.debug.xcconfig"; path = "Target Support Files/Pods-ImageNotifi/Pods-ImageNotifi.debug.xcconfig"; sourceTree = ""; }; 64F2A611E6EF486C8D3FB82C /* Roboto.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Roboto.ttf; path = ../src/assets/fonts/Roboto.ttf; sourceTree = ""; }; 65F56948860941D6BA55779F /* rubicon-icon-font.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = "rubicon-icon-font.ttf"; path = "../src/assets/fonts/rubicon-icon-font.ttf"; sourceTree = ""; }; 6D935B44FB5A4CF3BF4D01DF /* Ionicons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Ionicons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Ionicons.ttf"; sourceTree = ""; }; 7900A87FFF214846B5FE0430 /* Roboto-medium.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = "Roboto-medium.ttf"; path = "../src/assets/fonts/Roboto-medium.ttf"; sourceTree = ""; }; - 83345398C95A01BA9C82A26A /* Pods-Ecency.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency.release.xcconfig"; path = "Target Support Files/Pods-Ecency/Pods-Ecency.release.xcconfig"; sourceTree = ""; }; + 81B9802D36EADE78AC1698B2 /* Pods-ImageNotifi.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ImageNotifi.release.xcconfig"; path = "Target Support Files/Pods-ImageNotifi/Pods-ImageNotifi.release.xcconfig"; sourceTree = ""; }; 93B182C6FFA44610AB188D7C /* Entypo.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Entypo.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Entypo.ttf"; sourceTree = ""; }; + 93F4309F14D55B296FAB2A2B /* Pods-Ecency.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency.release.xcconfig"; path = "Target Support Files/Pods-Ecency/Pods-Ecency.release.xcconfig"; sourceTree = ""; }; 9464AFB033664B4F8E9F0BED /* AntDesign.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = AntDesign.ttf; path = "../node_modules/react-native-vector-icons/Fonts/AntDesign.ttf"; sourceTree = ""; }; 980BC9BC0D3B4AC69645C842 /* Zocial.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Zocial.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Zocial.ttf"; sourceTree = ""; }; 98D3D7C3AF354BF0987A2BFA /* Fontisto.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Fontisto.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Fontisto.ttf"; sourceTree = ""; }; 9BC08A790166415B9BB3F5CF /* FontAwesome5_Regular.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = FontAwesome5_Regular.ttf; path = "../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Regular.ttf"; sourceTree = ""; }; A239FC84622A4A9CA7950ED9 /* EvilIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = EvilIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/EvilIcons.ttf"; sourceTree = ""; }; + B2725EB8713842C347C76372 /* Pods-Ecency-EcencyTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ecency-EcencyTests.release.xcconfig"; path = "Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests.release.xcconfig"; sourceTree = ""; }; BB1093ACCD904E2883413214 /* FontAwesome5_Brands.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = FontAwesome5_Brands.ttf; path = "../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Brands.ttf"; sourceTree = ""; }; - E71848FA34FB051BB9C34796 /* Pods-ImageNotifi.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ImageNotifi.debug.xcconfig"; path = "Target Support Files/Pods-ImageNotifi/Pods-ImageNotifi.debug.xcconfig"; sourceTree = ""; }; ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; }; ED2971642150620600B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS12.0.sdk/System/Library/Frameworks/JavaScriptCore.framework; sourceTree = DEVELOPER_DIR; }; F1D77AE9F7B24CF19834052B /* Sansation_Bold.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Sansation_Bold.ttf; path = ../src/assets/fonts/Sansation_Bold.ttf; sourceTree = ""; }; - FA5F73032F66B1EBAA61B851 /* libPods-Ecency.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Ecency.a"; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -171,7 +171,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 04D1BA15BBCF7F2B9E3612BF /* libPods-Ecency-EcencyTests.a in Frameworks */, + CAB37987FC01E2F3B078A1B0 /* libPods-Ecency-EcencyTests.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -186,7 +186,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 3ABD43432246ECAC42DCEE31 /* libPods-ImageNotifi.a in Frameworks */, + 559F6876CF90046F127B01A7 /* libPods-ImageNotifi.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -196,7 +196,7 @@ files = ( 05B6C49424C306CE00B7FA60 /* StoreKit.framework in Frameworks */, 065B9DDE2930E42A004310E4 /* hermes.xcframework in Frameworks */, - 31856ADD6C0311522CA1DFA7 /* libPods-Ecency.a in Frameworks */, + 591DCA36C99F9CEF3DDF91F0 /* libPods-Ecency.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -280,12 +280,12 @@ 258E34A3BDFFFBF80D598187 /* Pods */ = { isa = PBXGroup; children = ( - 0AA04D912D96044AECF20A65 /* Pods-Ecency.debug.xcconfig */, - 83345398C95A01BA9C82A26A /* Pods-Ecency.release.xcconfig */, - 404E707BFB0A754BDB18D41C /* Pods-Ecency-EcencyTests.debug.xcconfig */, - 1DFEA0938900B7C7E419498A /* Pods-Ecency-EcencyTests.release.xcconfig */, - E71848FA34FB051BB9C34796 /* Pods-ImageNotifi.debug.xcconfig */, - 4CA976A51F8781F23710B585 /* Pods-ImageNotifi.release.xcconfig */, + 56F7FFCAA3257C590A314DE7 /* Pods-Ecency.debug.xcconfig */, + 93F4309F14D55B296FAB2A2B /* Pods-Ecency.release.xcconfig */, + 347F92D26DDA1405D2BF50E8 /* Pods-Ecency-EcencyTests.debug.xcconfig */, + B2725EB8713842C347C76372 /* Pods-Ecency-EcencyTests.release.xcconfig */, + 64961AAC9D95CBD0493E4F11 /* Pods-ImageNotifi.debug.xcconfig */, + 81B9802D36EADE78AC1698B2 /* Pods-ImageNotifi.release.xcconfig */, ); path = Pods; sourceTree = ""; @@ -299,9 +299,9 @@ 58190B3B23294814000EA0E1 /* StoreKit.framework */, ED297162215061F000B7C4FE /* JavaScriptCore.framework */, ED2971642150620600B7C4FE /* JavaScriptCore.framework */, - FA5F73032F66B1EBAA61B851 /* libPods-Ecency.a */, - 0FDDF70C668E24276B7F7D91 /* libPods-Ecency-EcencyTests.a */, - 573C027160DB8491D45BFEA8 /* libPods-ImageNotifi.a */, + 1139E19235945FF6A16519D6 /* libPods-Ecency.a */, + 0000A09C65210B9482224F67 /* libPods-Ecency-EcencyTests.a */, + 319533F3C37053AA08129D61 /* libPods-ImageNotifi.a */, ); name = Frameworks; sourceTree = ""; @@ -400,12 +400,12 @@ isa = PBXNativeTarget; buildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "EcencyTests" */; buildPhases = ( - C54D84D662D6C182DE045D38 /* [CP] Check Pods Manifest.lock */, + BE32AC858A4F124E62B8B1BF /* [CP] Check Pods Manifest.lock */, 00E356EA1AD99517003FC87E /* Sources */, 00E356EB1AD99517003FC87E /* Frameworks */, 00E356EC1AD99517003FC87E /* Resources */, - 5F1FB1470958FA150303E0F1 /* [CP] Embed Pods Frameworks */, - CAF063D667FC5B3B68512988 /* [CP] Copy Pods Resources */, + F856016C95FAF77E194BC8C8 /* [CP] Embed Pods Frameworks */, + 21FB1EC5817ACC0F97DA5669 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -437,7 +437,7 @@ isa = PBXNativeTarget; buildConfigurationList = 057A51A92AD4962400E9A768 /* Build configuration list for PBXNativeTarget "ImageNotifi" */; buildPhases = ( - 1A5C8F8F41BED1BE8F97C47C /* [CP] Check Pods Manifest.lock */, + 8216E0EEF7832DB97AAF1654 /* [CP] Check Pods Manifest.lock */, 057A519C2AD4962300E9A768 /* Sources */, 057A519D2AD4962300E9A768 /* Frameworks */, 057A519E2AD4962300E9A768 /* Resources */, @@ -455,7 +455,7 @@ isa = PBXNativeTarget; buildConfigurationList = 05B6C4B424C306CE00B7FA60 /* Build configuration list for PBXNativeTarget "Ecency" */; buildPhases = ( - A2B10E2CCC0492CF4778DDED /* [CP] Check Pods Manifest.lock */, + B8F91FD4FFA7AB8473EA7760 /* [CP] Check Pods Manifest.lock */, 05B6C48E24C306CE00B7FA60 /* Start Packager */, 05B6C48F24C306CE00B7FA60 /* Sources */, 05B6C49324C306CE00B7FA60 /* Frameworks */, @@ -464,9 +464,9 @@ 58C9F50524CE017800A026DD /* Embed App Extensions */, 05BAAAEE25BF43F80072EA01 /* ShellScript */, 3D1F6693773C4541A695BB3C /* Upload source maps to Bugsnag */, - C44924AC2FA92201E7EB2539 /* [CP] Embed Pods Frameworks */, - 7EEC7F0DE47D7C7CE8A3F289 /* [CP] Copy Pods Resources */, - DA796ED766580399CD1F9EFE /* [CP-User] [RNFB] Core Configuration */, + 59A6DED293C097CA3ABAE487 /* [CP] Embed Pods Frameworks */, + BD9420EA1BB9AAFB489AE3EF /* [CP] Copy Pods Resources */, + 53DC3559F8BD682DC0CA78DC /* [CP-User] [RNFB] Core Configuration */, ); buildRules = ( ); @@ -717,203 +717,7 @@ shellPath = /bin/sh; shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n"; }; - 1A5C8F8F41BED1BE8F97C47C /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-ImageNotifi-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 3D1F6693773C4541A695BB3C /* Upload source maps to Bugsnag */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Upload source maps to Bugsnag"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "SOURCE_MAP=\"$TMPDIR/$(md5 -qs \"$CONFIGURATION_BUILD_DIR\")-main.jsbundle.map\" ../node_modules/@bugsnag/react-native/bugsnag-react-native-xcode.sh"; - }; - 57F4EECD4004FE3420E6DF92 /* Bundle React Native Code And Images */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Bundle React Native Code And Images"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "export EXTRA_PACKAGER_ARGS=\"--sourcemap-output $TMPDIR/$(md5 -qs \"$CONFIGURATION_BUILD_DIR\")-main.jsbundle.map\"\nexport EXTRA_PACKAGER_ARGS=\"--sourcemap-output $CONFIGURATION_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/main.jsbundle.map\"\nexport NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh"; - }; - 5F1FB1470958FA150303E0F1 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests-frameworks.sh", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-DoubleConversion/double-conversion.framework/double-conversion", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-Glog/glog.framework/glog", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/OpenSSL-Universal/OpenSSL.framework/OpenSSL", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/hermes-engine/hermes.framework/hermes", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/double-conversion.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/glog.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/OpenSSL.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/hermes.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 7EEC7F0DE47D7C7CE8A3F289 /* [CP] Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Ecency/Pods-Ecency-resources.sh", - "${PODS_CONFIGURATION_BUILD_DIR}/RNImageCropPicker/QBImagePicker.bundle", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/AntDesign.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Entypo.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/EvilIcons.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Feather.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/FontAwesome.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Brands.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Regular.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Solid.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Fontisto.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Foundation.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Ionicons.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/MaterialIcons.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Octicons.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/SimpleLineIcons.ttf", - "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Zocial.ttf", - "${PODS_CONFIGURATION_BUILD_DIR}/React-Core/AccessibilityResources.bundle", - "${PODS_CONFIGURATION_BUILD_DIR}/TOCropViewController/TOCropViewControllerBundle.bundle", - ); - name = "[CP] Copy Pods Resources"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/QBImagePicker.bundle", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/AntDesign.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Entypo.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/EvilIcons.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Feather.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/FontAwesome.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/FontAwesome5_Brands.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/FontAwesome5_Regular.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/FontAwesome5_Solid.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Fontisto.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Foundation.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Ionicons.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/MaterialCommunityIcons.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/MaterialIcons.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Octicons.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/SimpleLineIcons.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Zocial.ttf", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/AccessibilityResources.bundle", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/TOCropViewControllerBundle.bundle", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency/Pods-Ecency-resources.sh\"\n"; - showEnvVarsInLog = 0; - }; - A2B10E2CCC0492CF4778DDED /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Ecency-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - C44924AC2FA92201E7EB2539 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Ecency/Pods-Ecency-frameworks.sh", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-DoubleConversion/double-conversion.framework/double-conversion", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-Glog/glog.framework/glog", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/OpenSSL-Universal/OpenSSL.framework/OpenSSL", - "${PODS_XCFRAMEWORKS_BUILD_DIR}/hermes-engine/hermes.framework/hermes", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/double-conversion.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/glog.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/OpenSSL.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/hermes.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency/Pods-Ecency-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - C54D84D662D6C182DE045D38 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Ecency-EcencyTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - CAF063D667FC5B3B68512988 /* [CP] Copy Pods Resources */ = { + 21FB1EC5817ACC0F97DA5669 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -967,7 +771,21 @@ shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests-resources.sh\"\n"; showEnvVarsInLog = 0; }; - DA796ED766580399CD1F9EFE /* [CP-User] [RNFB] Core Configuration */ = { + 3D1F6693773C4541A695BB3C /* Upload source maps to Bugsnag */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Upload source maps to Bugsnag"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "SOURCE_MAP=\"$TMPDIR/$(md5 -qs \"$CONFIGURATION_BUILD_DIR\")-main.jsbundle.map\" ../node_modules/@bugsnag/react-native/bugsnag-react-native-xcode.sh"; + }; + 53DC3559F8BD682DC0CA78DC /* [CP-User] [RNFB] Core Configuration */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -980,6 +798,188 @@ shellPath = /bin/sh; shellScript = "#!/usr/bin/env bash\n#\n# Copyright (c) 2016-present Invertase Limited & Contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this library except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nset -e\n\n_MAX_LOOKUPS=2;\n_SEARCH_RESULT=''\n_RN_ROOT_EXISTS=''\n_CURRENT_LOOKUPS=1\n_JSON_ROOT=\"'react-native'\"\n_JSON_FILE_NAME='firebase.json'\n_JSON_OUTPUT_BASE64='e30=' # { }\n_CURRENT_SEARCH_DIR=${PROJECT_DIR}\n_PLIST_BUDDY=/usr/libexec/PlistBuddy\n_TARGET_PLIST=\"${BUILT_PRODUCTS_DIR}/${INFOPLIST_PATH}\"\n_DSYM_PLIST=\"${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Info.plist\"\n\n# plist arrays\n_PLIST_ENTRY_KEYS=()\n_PLIST_ENTRY_TYPES=()\n_PLIST_ENTRY_VALUES=()\n\nfunction setPlistValue {\n echo \"info: setting plist entry '$1' of type '$2' in file '$4'\"\n ${_PLIST_BUDDY} -c \"Add :$1 $2 '$3'\" $4 || echo \"info: '$1' already exists\"\n}\n\nfunction getFirebaseJsonKeyValue () {\n if [[ ${_RN_ROOT_EXISTS} ]]; then\n ruby -e \"require 'rubygems';require 'json'; output=JSON.parse('$1'); puts output[$_JSON_ROOT]['$2']\"\n else\n echo \"\"\n fi;\n}\n\nfunction jsonBoolToYesNo () {\n if [[ $1 == \"false\" ]]; then\n echo \"NO\"\n elif [[ $1 == \"true\" ]]; then\n echo \"YES\"\n else echo \"NO\"\n fi\n}\n\necho \"info: -> RNFB build script started\"\necho \"info: 1) Locating ${_JSON_FILE_NAME} file:\"\n\nif [[ -z ${_CURRENT_SEARCH_DIR} ]]; then\n _CURRENT_SEARCH_DIR=$(pwd)\nfi;\n\nwhile true; do\n _CURRENT_SEARCH_DIR=$(dirname \"$_CURRENT_SEARCH_DIR\")\n if [[ \"$_CURRENT_SEARCH_DIR\" == \"/\" ]] || [[ ${_CURRENT_LOOKUPS} -gt ${_MAX_LOOKUPS} ]]; then break; fi;\n echo \"info: ($_CURRENT_LOOKUPS of $_MAX_LOOKUPS) Searching in '$_CURRENT_SEARCH_DIR' for a ${_JSON_FILE_NAME} file.\"\n _SEARCH_RESULT=$(find \"$_CURRENT_SEARCH_DIR\" -maxdepth 2 -name ${_JSON_FILE_NAME} -print | /usr/bin/head -n 1)\n if [[ ${_SEARCH_RESULT} ]]; then\n echo \"info: ${_JSON_FILE_NAME} found at $_SEARCH_RESULT\"\n break;\n fi;\n _CURRENT_LOOKUPS=$((_CURRENT_LOOKUPS+1))\ndone\n\nif [[ ${_SEARCH_RESULT} ]]; then\n _JSON_OUTPUT_RAW=$(cat \"${_SEARCH_RESULT}\")\n _RN_ROOT_EXISTS=$(ruby -e \"require 'rubygems';require 'json'; output=JSON.parse('$_JSON_OUTPUT_RAW'); puts output[$_JSON_ROOT]\" || echo '')\n\n if [[ ${_RN_ROOT_EXISTS} ]]; then\n if ! python3 --version >/dev/null 2>&1; then echo \"python3 not found, firebase.json file processing error.\" && exit 1; fi\n _JSON_OUTPUT_BASE64=$(python3 -c 'import json,sys,base64;print(base64.b64encode(bytes(json.dumps(json.loads(open('\"'${_SEARCH_RESULT}'\"', '\"'rb'\"').read())['${_JSON_ROOT}']), '\"'utf-8'\"')).decode())' || echo \"e30=\")\n fi\n\n _PLIST_ENTRY_KEYS+=(\"firebase_json_raw\")\n _PLIST_ENTRY_TYPES+=(\"string\")\n _PLIST_ENTRY_VALUES+=(\"$_JSON_OUTPUT_BASE64\")\n\n # config.app_data_collection_default_enabled\n _APP_DATA_COLLECTION_ENABLED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"app_data_collection_default_enabled\")\n if [[ $_APP_DATA_COLLECTION_ENABLED ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseDataCollectionDefaultEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_APP_DATA_COLLECTION_ENABLED\")\")\n fi\n\n # config.analytics_auto_collection_enabled\n _ANALYTICS_AUTO_COLLECTION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_auto_collection_enabled\")\n if [[ $_ANALYTICS_AUTO_COLLECTION ]]; then\n _PLIST_ENTRY_KEYS+=(\"FIREBASE_ANALYTICS_COLLECTION_ENABLED\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_AUTO_COLLECTION\")\")\n fi\n\n # config.analytics_collection_deactivated\n _ANALYTICS_DEACTIVATED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_collection_deactivated\")\n if [[ $_ANALYTICS_DEACTIVATED ]]; then\n _PLIST_ENTRY_KEYS+=(\"FIREBASE_ANALYTICS_COLLECTION_DEACTIVATED\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_DEACTIVATED\")\")\n fi\n\n # config.analytics_idfv_collection_enabled\n _ANALYTICS_IDFV_COLLECTION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_idfv_collection_enabled\")\n if [[ $_ANALYTICS_IDFV_COLLECTION ]]; then\n _PLIST_ENTRY_KEYS+=(\"GOOGLE_ANALYTICS_IDFV_COLLECTION_ENABLED\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_IDFV_COLLECTION\")\")\n fi\n\n # config.analytics_default_allow_ad_personalization_signals\n _ANALYTICS_PERSONALIZATION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"analytics_default_allow_ad_personalization_signals\")\n if [[ $_ANALYTICS_PERSONALIZATION ]]; then\n _PLIST_ENTRY_KEYS+=(\"GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_PERSONALIZATION\")\")\n fi\n\n # config.google_analytics_automatic_screen_reporting_enabled\n _ANALYTICS_AUTO_SCREEN_REPORTING=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"google_analytics_automatic_screen_reporting_enabled\")\n if [[ $_ANALYTICS_AUTO_SCREEN_REPORTING ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseAutomaticScreenReportingEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_ANALYTICS_AUTO_SCREEN_REPORTING\")\")\n fi\n\n # config.perf_auto_collection_enabled\n _PERF_AUTO_COLLECTION=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"perf_auto_collection_enabled\")\n if [[ $_PERF_AUTO_COLLECTION ]]; then\n _PLIST_ENTRY_KEYS+=(\"firebase_performance_collection_enabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_PERF_AUTO_COLLECTION\")\")\n fi\n\n # config.perf_collection_deactivated\n _PERF_DEACTIVATED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"perf_collection_deactivated\")\n if [[ $_PERF_DEACTIVATED ]]; then\n _PLIST_ENTRY_KEYS+=(\"firebase_performance_collection_deactivated\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_PERF_DEACTIVATED\")\")\n fi\n\n # config.messaging_auto_init_enabled\n _MESSAGING_AUTO_INIT=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"messaging_auto_init_enabled\")\n if [[ $_MESSAGING_AUTO_INIT ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseMessagingAutoInitEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_MESSAGING_AUTO_INIT\")\")\n fi\n\n # config.in_app_messaging_auto_colllection_enabled\n _FIAM_AUTO_INIT=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"in_app_messaging_auto_collection_enabled\")\n if [[ $_FIAM_AUTO_INIT ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseInAppMessagingAutomaticDataCollectionEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_FIAM_AUTO_INIT\")\")\n fi\n\n # config.app_check_token_auto_refresh\n _APP_CHECK_TOKEN_AUTO_REFRESH=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"app_check_token_auto_refresh\")\n if [[ $_APP_CHECK_TOKEN_AUTO_REFRESH ]]; then\n _PLIST_ENTRY_KEYS+=(\"FirebaseAppCheckTokenAutoRefreshEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"$(jsonBoolToYesNo \"$_APP_CHECK_TOKEN_AUTO_REFRESH\")\")\n fi\n\n # config.crashlytics_disable_auto_disabler - undocumented for now - mainly for debugging, document if becomes useful\n _CRASHLYTICS_AUTO_DISABLE_ENABLED=$(getFirebaseJsonKeyValue \"$_JSON_OUTPUT_RAW\" \"crashlytics_disable_auto_disabler\")\n if [[ $_CRASHLYTICS_AUTO_DISABLE_ENABLED == \"true\" ]]; then\n echo \"Disabled Crashlytics auto disabler.\" # do nothing\n else\n _PLIST_ENTRY_KEYS+=(\"FirebaseCrashlyticsCollectionEnabled\")\n _PLIST_ENTRY_TYPES+=(\"bool\")\n _PLIST_ENTRY_VALUES+=(\"NO\")\n fi\nelse\n _PLIST_ENTRY_KEYS+=(\"firebase_json_raw\")\n _PLIST_ENTRY_TYPES+=(\"string\")\n _PLIST_ENTRY_VALUES+=(\"$_JSON_OUTPUT_BASE64\")\n echo \"warning: A firebase.json file was not found, whilst this file is optional it is recommended to include it to configure firebase services in React Native Firebase.\"\nfi;\n\necho \"info: 2) Injecting Info.plist entries: \"\n\n# Log out the keys we're adding\nfor i in \"${!_PLIST_ENTRY_KEYS[@]}\"; do\n echo \" -> $i) ${_PLIST_ENTRY_KEYS[$i]}\" \"${_PLIST_ENTRY_TYPES[$i]}\" \"${_PLIST_ENTRY_VALUES[$i]}\"\ndone\n\nfor plist in \"${_TARGET_PLIST}\" \"${_DSYM_PLIST}\" ; do\n if [[ -f \"${plist}\" ]]; then\n\n # paths with spaces break the call to setPlistValue. temporarily modify\n # the shell internal field separator variable (IFS), which normally\n # includes spaces, to consist only of line breaks\n oldifs=$IFS\n IFS=\"\n\"\n\n for i in \"${!_PLIST_ENTRY_KEYS[@]}\"; do\n setPlistValue \"${_PLIST_ENTRY_KEYS[$i]}\" \"${_PLIST_ENTRY_TYPES[$i]}\" \"${_PLIST_ENTRY_VALUES[$i]}\" \"${plist}\"\n done\n\n # restore the original internal field separator value\n IFS=$oldifs\n else\n echo \"warning: A Info.plist build output file was not found (${plist})\"\n fi\ndone\n\necho \"info: <- RNFB build script finished\"\n"; }; + 57F4EECD4004FE3420E6DF92 /* Bundle React Native Code And Images */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Bundle React Native Code And Images"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "export EXTRA_PACKAGER_ARGS=\"--sourcemap-output $TMPDIR/$(md5 -qs \"$CONFIGURATION_BUILD_DIR\")-main.jsbundle.map\"\nexport EXTRA_PACKAGER_ARGS=\"--sourcemap-output $CONFIGURATION_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/main.jsbundle.map\"\nexport NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh"; + }; + 59A6DED293C097CA3ABAE487 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Ecency/Pods-Ecency-frameworks.sh", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-DoubleConversion/double-conversion.framework/double-conversion", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-Glog/glog.framework/glog", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/OpenSSL-Universal/OpenSSL.framework/OpenSSL", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/hermes-engine/hermes.framework/hermes", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/double-conversion.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/glog.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/OpenSSL.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/hermes.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency/Pods-Ecency-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 8216E0EEF7832DB97AAF1654 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-ImageNotifi-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + B8F91FD4FFA7AB8473EA7760 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Ecency-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + BD9420EA1BB9AAFB489AE3EF /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Ecency/Pods-Ecency-resources.sh", + "${PODS_CONFIGURATION_BUILD_DIR}/RNImageCropPicker/QBImagePicker.bundle", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/AntDesign.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Entypo.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/EvilIcons.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Feather.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/FontAwesome.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Brands.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Regular.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/FontAwesome5_Solid.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Fontisto.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Foundation.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Ionicons.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/MaterialIcons.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Octicons.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/SimpleLineIcons.ttf", + "${PODS_ROOT}/../../node_modules/react-native-vector-icons/Fonts/Zocial.ttf", + "${PODS_CONFIGURATION_BUILD_DIR}/React-Core/AccessibilityResources.bundle", + "${PODS_CONFIGURATION_BUILD_DIR}/TOCropViewController/TOCropViewControllerBundle.bundle", + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/QBImagePicker.bundle", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/AntDesign.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Entypo.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/EvilIcons.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Feather.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/FontAwesome.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/FontAwesome5_Brands.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/FontAwesome5_Regular.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/FontAwesome5_Solid.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Fontisto.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Foundation.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Ionicons.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/MaterialCommunityIcons.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/MaterialIcons.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Octicons.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/SimpleLineIcons.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Zocial.ttf", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/AccessibilityResources.bundle", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/TOCropViewControllerBundle.bundle", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency/Pods-Ecency-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + BE32AC858A4F124E62B8B1BF /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Ecency-EcencyTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + F856016C95FAF77E194BC8C8 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests-frameworks.sh", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-DoubleConversion/double-conversion.framework/double-conversion", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/Flipper-Glog/glog.framework/glog", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/OpenSSL-Universal/OpenSSL.framework/OpenSSL", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/hermes-engine/hermes.framework/hermes", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/double-conversion.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/glog.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/OpenSSL.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/hermes.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Ecency-EcencyTests/Pods-Ecency-EcencyTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; FD10A7F122414F3F0027D42C /* Start Packager */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -1087,7 +1087,7 @@ /* Begin XCBuildConfiguration section */ 00E356F61AD99517003FC87E /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 404E707BFB0A754BDB18D41C /* Pods-Ecency-EcencyTests.debug.xcconfig */; + baseConfigurationReference = 347F92D26DDA1405D2BF50E8 /* Pods-Ecency-EcencyTests.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; @@ -1124,7 +1124,7 @@ }; 00E356F71AD99517003FC87E /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 1DFEA0938900B7C7E419498A /* Pods-Ecency-EcencyTests.release.xcconfig */; + baseConfigurationReference = B2725EB8713842C347C76372 /* Pods-Ecency-EcencyTests.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; @@ -1236,7 +1236,7 @@ }; 057A51AA2AD4962400E9A768 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = E71848FA34FB051BB9C34796 /* Pods-ImageNotifi.debug.xcconfig */; + baseConfigurationReference = 64961AAC9D95CBD0493E4F11 /* Pods-ImageNotifi.debug.xcconfig */; buildSettings = { CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; @@ -1279,7 +1279,7 @@ }; 057A51AB2AD4962400E9A768 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 4CA976A51F8781F23710B585 /* Pods-ImageNotifi.release.xcconfig */; + baseConfigurationReference = 81B9802D36EADE78AC1698B2 /* Pods-ImageNotifi.release.xcconfig */; buildSettings = { CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; @@ -1322,7 +1322,7 @@ }; 05B6C4B524C306CE00B7FA60 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 0AA04D912D96044AECF20A65 /* Pods-Ecency.debug.xcconfig */; + baseConfigurationReference = 56F7FFCAA3257C590A314DE7 /* Pods-Ecency.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; @@ -1407,7 +1407,7 @@ }; 05B6C4B624C306CE00B7FA60 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 83345398C95A01BA9C82A26A /* Pods-Ecency.release.xcconfig */; + baseConfigurationReference = 93F4309F14D55B296FAB2A2B /* Pods-Ecency.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; diff --git a/ios/Podfile.lock b/ios/Podfile.lock index 5eb2d968e..91201ebf8 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -653,6 +653,9 @@ PODS: - React-RCTImage - RNSVG (12.5.1): - React-Core + - RNTusClient (1.1.0): + - React-Core + - TUSKit (~> 1.4.2) - RNVectorIcons (6.7.0): - React - SDWebImage (5.11.1): @@ -667,6 +670,7 @@ PODS: - TOCropViewController (2.6.1) - toolbar-android (0.2.1): - React + - TUSKit (1.4.2) - Yoga (1.14.0) - YogaKit (1.18.1): - Yoga (~> 1.14) @@ -780,6 +784,7 @@ DEPENDENCIES: - RNReanimated (from `../node_modules/react-native-reanimated`) - RNScreens (from `../node_modules/react-native-screens`) - RNSVG (from `../node_modules/react-native-svg`) + - RNTusClient (from `../node_modules/react-native-tus-client`) - RNVectorIcons (from `../node_modules/react-native-vector-icons`) - TcpSockets (from `../node_modules/react-native-tcp`) - "toolbar-android (from `../node_modules/@react-native-community/toolbar-android`)" @@ -819,6 +824,7 @@ SPEC REPOS: - SDWebImageWebPCoder - SocketRocket - TOCropViewController + - TUSKit - YogaKit EXTERNAL SOURCES: @@ -986,6 +992,8 @@ EXTERNAL SOURCES: :path: "../node_modules/react-native-screens" RNSVG: :path: "../node_modules/react-native-svg" + RNTusClient: + :path: "../node_modules/react-native-tus-client" RNVectorIcons: :path: "../node_modules/react-native-vector-icons" TcpSockets: @@ -1106,6 +1114,7 @@ SPEC CHECKSUMS: RNReanimated: 6668b0587bebd4b15dd849b99e5a9c70fc12ed95 RNScreens: 4830eb40e0793b38849965cd27f4f3a7d7bc65c1 RNSVG: d7d7bc8229af3842c9cfc3a723c815a52cdd1105 + RNTusClient: b90393226531c118c4716a2b71128e3b9d9c77ee RNVectorIcons: 368d6d8b8301224e5ffb6254191f4f8876c2be0d SDWebImage: a7f831e1a65eb5e285e3fb046a23fcfbf08e696d SDWebImageWebPCoder: 908b83b6adda48effe7667cd2b7f78c897e5111d @@ -1113,6 +1122,7 @@ SPEC CHECKSUMS: TcpSockets: 4ef55305239923b343ed0a378b1fac188b1373b0 TOCropViewController: edfd4f25713d56905ad1e0b9f5be3fbe0f59c863 toolbar-android: 2a73856e98b750d7e71ce4644d3f41cc98211719 + TUSKit: 4bcc2fe13e1b4d6c3bfbaca57d64e64c1be31201 Yoga: 92d086bb705a41cc588599b51db726ba7b1d341c YogaKit: f782866e155069a2cca2517aafea43200b01fd5a diff --git a/package.json b/package.json index 40cac43b3..353cb8483 100644 --- a/package.json +++ b/package.json @@ -155,6 +155,7 @@ "react-native-svg": "^12.1.1", "react-native-swiper": "^1.6.0-rc.3", "react-native-tcp": "^4.0.0", + "react-native-tus-client": "^1.1.0", "react-native-udp": "^4.1.4", "react-native-unique-id": "^2.0.0", "react-native-vector-icons": "^6.6.0", @@ -206,7 +207,6 @@ "eslint-plugin-react": "^7.13.0", "eslint-plugin-react-hooks": "^2.3.0", "eslint-plugin-react-native": "^3.7.0", - "react-query-native-devtools": "^4.0.0", "husky": "^3.1.0", "jest": "^26.6.3", "lint-staged": "^7.2.0", @@ -214,6 +214,7 @@ "prettier": "^2.0.2", "prettier-eslint": "^9.0.1", "react-native-codegen": "^0.0.13", + "react-query-native-devtools": "^4.0.0", "react-test-renderer": "18.1.0", "reactotron-react-native": "^5.0.3", "reactotron-redux": "^3.1.3", diff --git a/patches/react-native-tus-client+1.1.0.patch b/patches/react-native-tus-client+1.1.0.patch new file mode 100644 index 000000000..1002fdb68 --- /dev/null +++ b/patches/react-native-tus-client+1.1.0.patch @@ -0,0 +1,11 @@ +diff --git a/node_modules/react-native-tus-client/RNTusClient.podspec b/node_modules/react-native-tus-client/RNTusClient.podspec +index b855287..3f49b50 100644 +--- a/node_modules/react-native-tus-client/RNTusClient.podspec ++++ b/node_modules/react-native-tus-client/RNTusClient.podspec +@@ -15,5 +15,5 @@ Pod::Spec.new do |s| + s.ios.deployment_target = '8.0' + + s.dependency 'React-Core' +- s.dependency 'TUSKit' ++ s.dependency 'TUSKit', '~> 1.4.2' + end diff --git a/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx b/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx index 522a460e7..a2311c9f2 100644 --- a/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx +++ b/src/components/uploadsGalleryModal/children/speakUploaderModal.tsx @@ -3,23 +3,28 @@ import { useRef } from 'react'; import { View, Text, TouchableOpacity, Image, TextInput } from 'react-native'; import ActionSheet from 'react-native-actions-sheet'; import EStyleSheet from 'react-native-extended-stylesheet'; +import { Video } from 'react-native-image-crop-picker'; import styles from '../styles/speakUploaderModal.styles'; import { MainButton } from '../../mainButton'; -import { Video } from 'react-native-image-crop-picker'; -import { uploadVideo } from '../../../providers/speak/speak'; +import { uploadFile, uploadVideoInfo } from '../../../providers/speak/speak'; +import { useAppSelector } from '../../../hooks'; -export const SpeakUploaderModal = forwardRef(({}, ref) => { +export const SpeakUploaderModal = forwardRef(({ }, ref) => { const sheetModalRef = useRef(); - const [image1, setImage1] = useState(null); - const [image2, setImage2] = useState(null); + const currentAccount = useAppSelector(state => state.account.currentAccount); + const pinHash = useAppSelector(state => state.application.pin); + + const [selectedThumb, setSelectedThumb] = useState(null); const [title, setTitle] = useState(''); const [isUploading, setIsUploading] = useState(false); + const [uploadProgress, setUploadProgress] = useState(0); + + const [selectedVido, setSelectedVideo] = useState