react-native#InteractionManager JavaScript Examples

The following examples show how to use react-native#InteractionManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: helpers.js    From filen-mobile with GNU Affero General Public License v3.0 6 votes vote down vote up
export function convertUint8ArrayToBinaryStringAsync(u8Array){
    return new Promise((resolve) => {
        InteractionManager.runAfterInteractions(() => {
            let i, len = u8Array.length, b_str = ""

            for (i = 0; i < len; i++){
                b_str += String.fromCharCode(u8Array[i])
            }

            return resolve(b_str)
        })
    })
}
Example #2
Source File: index.js    From react-native-bitmap-color-picker with MIT License 6 votes vote down vote up
measurePickerContainer() {
        // we always measure because layout is the same even though picker is moved on the page
        InteractionManager.runAfterInteractions(() => {
            // measure only after (possible) animation ended
            this.pickerContainer && this.pickerContainer.measureInWindow((pageX, pageY, width, height ) => {
                // picker position in the screen
                this._pageX = pageX;
                this._pageY = pageY;
            });
        });
    }
Example #3
Source File: helpers.js    From filen-mobile with GNU Affero General Public License v3.0 6 votes vote down vote up
fetchArrayBuffer = ({ url, timeout = 3600000 }) => {
    return new Promise((resolve, reject) => {
        InteractionManager.runAfterInteractions(() => {
            const request = new XMLHttpRequest()

            request.open("GET", url, true)
            request.responseType = "arraybuffer"
            request.timeout = timeout

            request.onloadend = () => {
                const response = request.response

                if(typeof response == "object"){
                    if(typeof response.byteLength == "number"){
                        if(response.byteLength > 0){
                            resolve(response)
                        }
                    }
                    else{
                        reject(new Error("Response is not an arrayBuffer"))
                    }
                }
                else{
                    reject(new Error("Response is not an arrayBuffer"))
                }
            }

            request.onerror = (err) => {
                reject(err)
            }

            request.send()
        })
    })
}
Example #4
Source File: helpers.js    From filen-mobile with GNU Affero General Public License v3.0 6 votes vote down vote up
uInt8ArrayConcatAsync = (arrays) => {
    return new Promise((resolve) => {
        InteractionManager.runAfterInteractions(() => {
            // sum of individual array lengths
            let totalLength = arrays.reduce((acc, value) => acc + value.length, 0);
        
            if (!arrays.length) return null;
        
            let result = new Uint8Array(totalLength);
        
            // for each array - copy it over result
            // next array is copied right after the previous one
            let length = 0;
            for(let array of arrays) {
            result.set(array, length);
            length += array.length;
            }

            totalLength = null
            length = null
            arrays = null
        
            return resolve(result);
        })
    })
}
Example #5
Source File: helpers.js    From filen-mobile with GNU Affero General Public License v3.0 6 votes vote down vote up
export function convertBinaryStringToUint8ArrayAsync(bStr) {
    return new Promise((resolve) => {
        InteractionManager.runAfterInteractions(() => {
            var i, len = bStr.length, u8_array = new Uint8Array(len);

            for (var i = 0; i < len; i++) {
                u8_array[i] = bStr.charCodeAt(i);
            }

            return resolve(u8_array);
        })
    })
}
Example #6
Source File: helpers.js    From filen-mobile with GNU Affero General Public License v3.0 5 votes vote down vote up
arrayBufferToBase64Async = (arrayBuffer) => {
    return new Promise((resolve, reject) => {
        InteractionManager.runAfterInteractions(() => {
            return resolve(cppBase64.fromByteArray(new Uint8Array(arrayBuffer)))
        })
    })
}
Example #7
Source File: helpers.js    From filen-mobile with GNU Affero General Public License v3.0 5 votes vote down vote up
base64ToArrayBufferAsync = (b64) => {
    return new Promise((resolve) => {
        InteractionManager.runAfterInteractions(() => {
            return resolve(cppBase64.toByteArray(b64))
        })
    })
}
Example #8
Source File: helpers.js    From filen-mobile with GNU Affero General Public License v3.0 5 votes vote down vote up
arrayBufferToHexAsync = (buffer) => {
    return new Promise((resolve) => {
        InteractionManager.runAfterInteractions(() => {
            return resolve([...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, "0")).join(""))
        })
    })
}
Example #9
Source File: tagEditor.js    From haven with MIT License 5 votes vote down vote up
componentDidMount() {
    InteractionManager.addListener('interactionStart', () => {
      Keyboard.dismiss();
    });
    this.focusListener = this.props.navigation.addListener('didFocus', this.setInputFocus);
  }
Example #10
Source File: index.service.js    From real-frontend with GNU General Public License v3.0 5 votes vote down vote up
ProfileService = ({ children, navigation }) => {
  const dispatch = useDispatch()
  const authUser = useSelector(state => state.auth.user)
  const usersGetProfile = useSelector(state => state.users.usersGetProfile)
  const usersGetProfileCache = useSelector(state => state.users.usersGetProfileCache)
  const usersBlock = useSelector(state => state.users.usersBlock)
  const usersUnblock = useSelector(state => state.users.usersUnblock)
  const postsStoriesGet = useSelector(state => state.posts.postsStoriesGet)
  const usersFollow = useSelector(state => state.users.usersFollow)
  const usersUnfollow = useSelector(state => state.users.usersUnfollow)
  const userId = navigation.getParam('userId')

  const usersGetProfileRequest = ({ userId }) => 
    dispatch(usersActions.usersGetProfileRequest({ userId }))

  const postsStoriesGetRequest = ({ userId }) =>
    dispatch(postsActions.postsStoriesGetRequest({ userId }))

  const usersUnblockRequest = ({ userId }) =>
    dispatch(usersActions.usersUnblockRequest({ userId }))

  const usersBlockRequest = ({ userId }) =>
    dispatch(usersActions.usersBlockRequest({ userId }))

  const usersFollowRequest = ({ userId }) =>
    dispatch(usersActions.usersFollowRequest({ userId }))
  
  const usersUnfollowRequest = ({ userId }) =>
    dispatch(usersActions.usersUnfollowRequest({ userId }))

  useEffect(() => {
    if (usersBlock.status === 'success') {
      dispatch(usersActions.usersBlockIdle())
    }

    if (usersUnblock.status === 'success') {
      dispatch(usersActions.usersUnblockIdle())
    }
  }, [
    usersBlock.status,
    usersUnblock.status,
  ])

  useEffect(() => {
    InteractionManager.runAfterInteractions(() => {
      usersGetProfileRequest({ userId })
      postsStoriesGetRequest({ userId })
    })
  }, [userId])

  return children({
    authUser,
    usersGetProfile: usersServices.cachedUsersGetProfile(usersGetProfile, usersGetProfileCache, pathOr({}, ['state', 'params'], navigation)),
    usersGetProfileRequest,
    postsStoriesGet,
    postsStoriesGetRequest,
    usersUnblock,
    usersUnblockRequest,
    usersBlock,
    usersBlockRequest,
    usersFollow,
    usersFollowRequest,
    usersUnfollow,
    usersUnfollowRequest,
  })
}
Example #11
Source File: index.service.js    From real-frontend with GNU General Public License v3.0 5 votes vote down vote up
SimpleCacheService = ({ children, source, priorityIndex }) => {
  const dispatch = useDispatch()

  const signature = generateSignature(source.uri)

  const cacheFetchItemPath = useSelector(cacheFetchItemPathSelector(signature.partial))

  const channelType = ['64p', '480p', '1080p', '4k'].find(resolution => includes(resolution, source.uri || ''))

  const cacheFetchRequest = () => {
    if (typeof source.uri !== 'string' || !source.uri.length) {
      return
    }

    if (channelType === '64p') {
      dispatch(cacheActions.cacheFetch64pRequest({ priorityIndex, source: source.uri }))
    } else if (channelType === '480p') {
      dispatch(cacheActions.cacheFetch480pRequest({ priorityIndex, source: source.uri }))
    } else if (channelType === '1080p') {
      dispatch(cacheActions.cacheFetch1080pRequest({ priorityIndex, source: source.uri }))
    } else if (channelType === '4k') {
      dispatch(cacheActions.cacheFetch4kRequest({ priorityIndex, source: source.uri }))
    } else {
      dispatch(cacheActions.cacheFetchRequest({ priorityIndex, source: source.uri }))
    }
  }

  useEffect(() => {
    InteractionManager.runAfterInteractions(() => {
      cacheFetchRequest()
    })
  }, [])

  const uri = signature.isRemote ? cacheFetchItemPath : source.uri

  const onError = () => {
    cacheFetchRequest()
  }

  if (!uri) {
    return null
  }

  return children({
    source: { uri },
    onError,
  })
}
Example #12
Source File: index.js    From react-native-expo-cached-image with MIT License 5 votes vote down vote up
async componentDidMount() {
    this._interaction = InteractionManager.runAfterInteractions(async () => {
      if (this.props.source.uri) {
        const filesystemURI = await this.getImageFilesystemKey(this.props.source.uri);
        await this.loadImage(filesystemURI, this.props.source.uri);
      }
    });
  }
Example #13
Source File: navigation.js    From lx-music-mobile with Apache License 2.0 4 votes vote down vote up
export function pushPlayDetailScreen(componentId, id) {
  /*
    Navigation.setDefaultOptions({
      topBar: {
        background: {
          color: '#039893',
        },
        title: {
          color: 'white',
        },
        backButton: {
          title: '', // Remove previous screen name from back button
          color: 'white',
        },
        buttonColor: 'white',
      },
      statusBar: {
        style: 'light',
      },
      layout: {
        orientation: ['portrait'],
      },
      bottomTabs: {
        titleDisplayMode: 'alwaysShow',
      },
      bottomTab: {
        textColor: 'gray',
        selectedTextColor: 'black',
        iconColor: 'gray',
        selectedIconColor: 'black',
      },
    })
  */
  InteractionManager.runAfterInteractions(() => {
    const theme = getTheme()

    Navigation.push(componentId, {
      component: {
        name: PLAY_DETAIL_SCREEN,
        options: {
          topBar: {
            visible: false,
            height: 0,
            drawBehind: false,
          },
          statusBar: {
            drawBehind: true,
            visible: true,
            style: getStatusBarStyle(),
            backgroundColor: 'transparent',
          },
          navigationBar: {
            // visible: false,
            backgroundColor: theme.primary,
          },
          layout: {
            componentBackgroundColor: theme.primary,
          },
          animations: {
            push: {
              sharedElementTransitions: [
                {
                  fromId: `pic${id}`,
                  toId: `pic${id}Dest`,
                  interpolation: { type: 'spring' },
                },
              ],
              elementTransitions: [
                {
                  id: 'header',
                  alpha: {
                    from: 0, // We don't declare 'to' value as that is the element's current alpha value, here we're essentially animating from 0 to 1
                    duration: 300,
                  },
                  translationY: {
                    from: -32, // Animate translationY from 16dp to 0dp
                    duration: 300,
                  },
                },
                {
                  id: 'pageIndicator',
                  alpha: {
                    from: 0, // We don't declare 'to' value as that is the element's current alpha value, here we're essentially animating from 0 to 1
                    duration: 300,
                  },
                  translationX: {
                    from: -32, // Animate translationY from 16dp to 0dp
                    duration: 300,
                  },
                },
                {
                  id: 'player',
                  alpha: {
                    from: 0, // We don't declare 'to' value as that is the element's current alpha value, here we're essentially animating from 0 to 1
                    duration: 300,
                  },
                  translationY: {
                    from: 32, // Animate translationY from 16dp to 0dp
                    duration: 300,
                  },
                },
              ],
              // content: {
              //   translationX: {
              //     from: Dimensions.get('window').width,
              //     to: 0,
              //     duration: 300,
              //   },
              // },
            },
            pop: {
              content: {
                translationX: {
                  from: 0,
                  to: Dimensions.get('window').width,
                  duration: 300,
                },
              },
            },
          },
        },
      },
    })
  })
}
Example #14
Source File: navigation.js    From lx-music-mobile with Apache License 2.0 4 votes vote down vote up
export function pushSonglistDetailScreen(componentId, id) {
  const theme = getTheme()
  InteractionManager.runAfterInteractions(() => {
    Navigation.push(componentId, {
      component: {
        name: SONGLIST_DETAIL_SCREEN,
        options: {
          topBar: {
            visible: false,
            height: 0,
            drawBehind: false,
          },
          statusBar: {
            drawBehind: true,
            visible: true,
            style: getStatusBarStyle(),
            backgroundColor: 'transparent',
          },
          navigationBar: {
            // visible: false,
            backgroundColor: theme.primary,
          },
          layout: {
            componentBackgroundColor: theme.primary,
          },
          animations: {
            push: {
              sharedElementTransitions: [
                {
                  fromId: `pic${id}`,
                  toId: `pic${id}Dest`,
                  interpolation: { type: 'spring' },
                },
              ],
              elementTransitions: [
                {
                  id: 'title',
                  alpha: {
                    from: 0, // We don't declare 'to' value as that is the element's current alpha value, here we're essentially animating from 0 to 1
                    duration: 300,
                  },
                  translationX: {
                    from: 16, // Animate translationX from 16dp to 0dp
                    duration: 300,
                  },
                },
              ],
              // content: {
              //   scaleX: {
              //     from: 1.2,
              //     to: 1,
              //     duration: 200,
              //   },
              //   scaleY: {
              //     from: 1.2,
              //     to: 1,
              //     duration: 200,
              //   },
              //   alpha: {
              //     from: 0,
              //     to: 1,
              //     duration: 200,
              //   },
              // },
            },
            pop: {
              sharedElementTransitions: [
                {
                  fromId: `pic${id}Dest`,
                  toId: `pic${id}`,
                  interpolation: { type: 'spring' },
                },
              ],
              elementTransitions: [
                {
                  id: 'title',
                  alpha: {
                    to: 0, // We don't declare 'to' value as that is the element's current alpha value, here we're essentially animating from 0 to 1
                    duration: 300,
                  },
                  translationX: {
                    to: 16, // Animate translationX from 16dp to 0dp
                    duration: 300,
                  },
                },
              ],
              // content: {
              //   alpha: {
              //     from: 1,
              //     to: 0,
              //     duration: 200,
              //   },
              // },
            },
          },
        },
      },
    })
  })
}
Example #15
Source File: navigation.js    From lx-music-mobile with Apache License 2.0 4 votes vote down vote up
export function pushCommentScreen(componentId) {
  /*
    Navigation.setDefaultOptions({
      topBar: {
        background: {
          color: '#039893',
        },
        title: {
          color: 'white',
        },
        backButton: {
          title: '', // Remove previous screen name from back button
          color: 'white',
        },
        buttonColor: 'white',
      },
      statusBar: {
        style: 'light',
      },
      layout: {
        orientation: ['portrait'],
      },
      bottomTabs: {
        titleDisplayMode: 'alwaysShow',
      },
      bottomTab: {
        textColor: 'gray',
        selectedTextColor: 'black',
        iconColor: 'gray',
        selectedIconColor: 'black',
      },
    })
  */
  InteractionManager.runAfterInteractions(() => {
    const theme = getTheme()
    Navigation.push(componentId, {
      component: {
        name: COMMENT_SCREEN,
        options: {
          topBar: {
            visible: false,
            height: 0,
            drawBehind: false,
          },
          statusBar: {
            drawBehind: true,
            visible: true,
            style: getStatusBarStyle(),
            backgroundColor: 'transparent',
          },
          navigationBar: {
            // visible: false,
            backgroundColor: theme.primary,
          },
          layout: {
            componentBackgroundColor: theme.primary,
          },
          animations: {
            push: {
              content: {
                translationX: {
                  from: Dimensions.get('window').width,
                  to: 0,
                  duration: 300,
                },
              },
            },
            pop: {
              content: {
                translationX: {
                  from: 0,
                  to: Dimensions.get('window').width,
                  duration: 300,
                },
              },
            },
          },
        },
      },
    })
  })
}
Example #16
Source File: MyList.js    From lx-music-mobile with Apache License 2.0 4 votes vote down vote up
ImportExport = ({ actionType, visible, hide, selectedListRef }) => {
  const [title, setTitle] = useState('')
  const [dirOnly, setDirOnly] = useState(false)
  const setList = useDispatch('list', 'setList')
  const createUserList = useDispatch('list', 'createUserList')
  const { t } = useTranslation()
  useEffect(() => {
    switch (actionType) {
      case 'import':
        setTitle(t('list_import_part_desc'))
        setDirOnly(false)
        break
      case 'export':
      default:
        setTitle(t('list_export_part_desc'))
        setDirOnly(true)
        break
    }
  }, [actionType, t])

  const onConfirmPath = useCallback(path => {
    hide()
    switch (actionType) {
      case 'import':
        toast(t('setting_backup_part_import_list_tip_unzip'))
        importList(path).then(async listData => {
          if (listData.type != 'playListPart') return showImportTip(listData.type)
          const targetList = global.allList[listData.data.id]
          if (targetList) {
            const confirm = await confirmDialog({
              message: t('list_import_part_confirm', { importName: listData.data.name, localName: targetList.name }),
              cancelButtonText: t('list_import_part_button_cancel'),
              confirmButtonText: t('list_import_part_button_confirm'),
              bgClose: false,
            })
            if (confirm) {
              listData.data.name = targetList.name
              setList({
                name: listData.data.name,
                id: listData.data.id,
                list: listData.data.list,
                source: listData.data.source,
                sourceListId: listData.data.sourceListId,
              })
              toast(t('setting_backup_part_import_list_tip_success'))
              return
            }
            listData.data.id += `__${Date.now()}`
          }
          createUserList({
            name: listData.data.name,
            id: listData.data.id,
            list: listData.data.list,
            source: listData.data.source,
            sourceListId: listData.data.sourceListId,
            position: Math.max(selectedListRef.current.index, -1),
          })
          toast(t('setting_backup_part_import_list_tip_success'))
        })
        break
      case 'export':
        InteractionManager.runAfterInteractions(() => {
          toast(t('setting_backup_part_export_list_tip_zip'))
          exportList(selectedListRef.current.listInfo, path).then(() => {
            toast(t('setting_backup_part_export_list_tip_success'))
          }).catch(err => {
            log.error(err.message)
            toast(t('setting_backup_part_export_list_tip_failed') + ': ' + err.message)
          })
        })
        break
    }
  }, [actionType, createUserList, hide, selectedListRef, setList, t])

  return (
    <ChoosePath
      visible={visible}
      hide={hide}
      title={title}
      dirOnly={dirOnly}
      filter={LXM_FILE_EXT_RXP}
      onConfirm={onConfirmPath} />
  )
}
Example #17
Source File: index.service.js    From real-frontend with GNU General Public License v3.0 4 votes vote down vote up
PostMediaService = ({ children, navigation, ...props }) => {
  const dispatch = useDispatch()
  const postId = path(['postId'])(navigation.getParam('post'))
  const userId = path(['postedBy', 'userId'])(navigation.getParam('post'))
  const postsSingleGet = useSelector(state => state.posts.postsSingleGet)
  const postsDelete = useSelector(state => state.posts.postsDelete)
  const postsGetTrendingPosts = useSelector(state => state.posts.postsGetTrendingPosts)
  const postsGetCache = useSelector(state => state.posts.postsGetCache)

  const layoutPostMediaItem = useSelector(state => state.layout.layoutPostMediaItem)
  const layoutPostMediaScroll = useSelector(state => state.layout.layoutPostMediaScroll)

  const [viewMore, setViewMore] = useState(true)
  const feedRef = useRef()

  const postsSingleGetRequest = ({ postId }) =>
    dispatch(postsActions.postsSingleGetRequest({ postId }))

  useEffect(() => {
    dispatch(postsActions.postsSingleGetRequest({ postId }))
  }, [postId])

  const layoutPostMediaScrollSuccess = (payload) =>
    dispatch(layoutActions.layoutPostMediaScrollSuccess(payload))

  const layoutPostMediaItemSuccess = (payload) =>
    dispatch(layoutActions.layoutPostMediaItemSuccess(payload))

  useEffect(() => {
    InteractionManager.runAfterInteractions(() => {
      dispatch(postsActions.postsReportPostViewsRequest({ postIds: [postId] }))
      dispatch(layoutActions.layoutPostMediaItemIdle())
      dispatch(layoutActions.layoutPostMediaScrollIdle())
    })
  }, [])

  useEffect(() => {
    if (postsDelete.status === 'success') {
      dispatch(postsActions.postsDeleteIdle())
    }
    if (postsDelete.status === 'loading') {
      navigation.goBack()
    }
  }, [postsDelete.status])

  useDebounce(() => {
    const range = Object.keys(layoutPostMediaItem.data)
    const goal = layoutPostMediaScroll.data.y
    
    if (!range.length || !goal) { return }
    
    const closest = range.reduce((prev, curr) =>
      (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev)
    )
    
    const closestPostId = layoutPostMediaItem.data[closest].postId
    dispatch(postsActions.postsReportPostViewsRequest({ postIds: [closestPostId] }))

    setViewMore(postId === closestPostId)
  }, 1000, [layoutPostMediaScroll.data.y])

  const handleViewMorePosts = () => {
    const range = Object.keys(layoutPostMediaItem.data).sort((a, b) => a - b)
    const offset = parseInt(range[1], 10) - parseInt(range[0], 10)
    feedRef.current.scrollToOffset({ animated: true, offset })
  }

  return children({
    postsSingleGet: postsServices.cachedPostsSingleGet(postsSingleGet, navigation.getParam('post')),
    postsGetTrendingPosts: postsServices.cachedPostsGetTrendingPosts(postsGetTrendingPosts, postId),
    postsSingleGetRequest,
    ...props,
    postsMediaFeedGet: postsServices.cachedPostsMediaFeedGet(postsGetCache, userId, postId),
    onScroll: layoutPostMediaScrollSuccess,
    layoutPostMediaItemSuccess,
    layoutPostMediaScroll,
    viewMore,
    handleViewMorePosts,
    feedRef,
    routeName: navigation.getParam('routeName'),
  })
}