├── .watchmanconfig ├── example ├── .ruby-version ├── .bundle │ └── config ├── ios │ ├── File.swift │ ├── BidirectionalFlatlistExample │ │ ├── Images.xcassets │ │ │ ├── Contents.json │ │ │ └── AppIcon.appiconset │ │ │ │ └── Contents.json │ │ ├── AppDelegate.h │ │ ├── main.m │ │ ├── Info.plist │ │ ├── AppDelegate.mm │ │ └── LaunchScreen.storyboard │ ├── BidirectionalFlatlistExample-Bridging-Header.h │ ├── BidirectionalFlatlistExample.xcworkspace │ │ ├── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ │ └── contents.xcworkspacedata │ ├── Podfile │ ├── BidirectionalFlatlistExample.xcodeproj │ │ ├── xcshareddata │ │ │ └── xcschemes │ │ │ │ └── BidirectionalFlatlistExample.xcscheme │ │ └── project.pbxproj │ └── Podfile.lock ├── .eslintrc.js ├── android │ ├── app │ │ ├── debug.keystore │ │ ├── src │ │ │ ├── main │ │ │ │ ├── res │ │ │ │ │ ├── values │ │ │ │ │ │ ├── strings.xml │ │ │ │ │ │ └── styles.xml │ │ │ │ │ ├── mipmap-hdpi │ │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ │ ├── mipmap-mdpi │ │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ │ ├── mipmap-xhdpi │ │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ │ └── drawable │ │ │ │ │ │ └── rn_edit_text_material.xml │ │ │ │ ├── jni │ │ │ │ │ ├── MainApplicationModuleProvider.h │ │ │ │ │ ├── OnLoad.cpp │ │ │ │ │ ├── MainApplicationModuleProvider.cpp │ │ │ │ │ ├── MainComponentsRegistry.h │ │ │ │ │ ├── MainApplicationTurboModuleManagerDelegate.h │ │ │ │ │ ├── MainApplicationTurboModuleManagerDelegate.cpp │ │ │ │ │ ├── Android.mk │ │ │ │ │ └── MainComponentsRegistry.cpp │ │ │ │ ├── AndroidManifest.xml │ │ │ │ └── java │ │ │ │ │ └── com │ │ │ │ │ └── example │ │ │ │ │ └── reactnativebidirectionalflatlist │ │ │ │ │ ├── newarchitecture │ │ │ │ │ ├── components │ │ │ │ │ │ └── MainComponentsRegistry.java │ │ │ │ │ ├── modules │ │ │ │ │ │ └── MainApplicationTurboModuleManagerDelegate.java │ │ │ │ │ └── MainApplicationReactNativeHost.java │ │ │ │ │ ├── MainActivity.java │ │ │ │ │ └── MainApplication.java │ │ │ └── debug │ │ │ │ ├── AndroidManifest.xml │ │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── example │ │ │ │ └── reactnativebidirectionalflatlist │ │ │ │ └── ReactNativeFlipper.java │ │ ├── proguard-rules.pro │ │ └── build.gradle │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── settings.gradle │ ├── gradle.properties │ ├── build.gradle │ ├── gradlew.bat │ └── gradlew ├── index.tsx ├── Gemfile ├── react-native.config.js ├── babel.config.js ├── package.json ├── metro.config.js ├── Gemfile.lock └── src │ └── App.tsx ├── src ├── config.ts ├── __tests__ │ └── index.test.tsx ├── index.tsx ├── types.ts ├── BidirectionalFlatlist.ts ├── FlatList.tsx ├── hooks │ └── usePrerenderedData.tsx └── ScrollView.tsx ├── .gitattributes ├── tsconfig.build.json ├── babel.config.js ├── docu ├── prepend.gif ├── prepend.mov ├── remove-and-add.gif └── remove-and-add.mov ├── .eslintrc.js ├── .yarnrc ├── android ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── src │ └── main │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── com │ │ └── reactnativebidirectionalflatlist │ │ ├── BidirectionalFlatlistPackage.java │ │ ├── BidirectionalFlatlistManager.java │ │ └── scroll │ │ └── ScrollView.java ├── gradle.properties ├── gradlew.bat ├── build.gradle └── gradlew ├── .editorconfig ├── lefthook.yml ├── tsconfig.json ├── scripts └── bootstrap.js ├── .gitignore ├── LICENSE ├── package.json ├── README.md └── CONTRIBUTING.md /.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /example/.ruby-version: -------------------------------------------------------------------------------- 1 | 2.7.4 2 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | export const MIN_INDEX = 1; 2 | -------------------------------------------------------------------------------- /src/__tests__/index.test.tsx: -------------------------------------------------------------------------------- 1 | it.todo('write a test'); 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | # specific for windows script files 3 | *.bat text eol=crlf -------------------------------------------------------------------------------- /example/.bundle/config: -------------------------------------------------------------------------------- 1 | BUNDLE_PATH: "vendor/bundle" 2 | BUNDLE_FORCE_RUBY_PLATFORM: 1 3 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "extends": "./tsconfig", 4 | "exclude": ["example"] 5 | } 6 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /docu/prepend.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/docu/prepend.gif -------------------------------------------------------------------------------- /docu/prepend.mov: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/docu/prepend.mov -------------------------------------------------------------------------------- /example/ios/File.swift: -------------------------------------------------------------------------------- 1 | // 2 | // File.swift 3 | // BidirectionalFlatlistExample 4 | // 5 | 6 | import Foundation 7 | -------------------------------------------------------------------------------- /docu/remove-and-add.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/docu/remove-and-add.gif -------------------------------------------------------------------------------- /docu/remove-and-add.mov: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/docu/remove-and-add.mov -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import { FlatList } from './FlatList'; 2 | 3 | export * from './types'; 4 | 5 | export default FlatList; 6 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['plugin:@typescript-eslint/recommended', 'plugin:react-hooks/recommended'], 3 | }; 4 | -------------------------------------------------------------------------------- /.yarnrc: -------------------------------------------------------------------------------- 1 | # Override Yarn command so we can automatically setup the repo on running `yarn` 2 | 3 | yarn-path "scripts/bootstrap.js" 4 | -------------------------------------------------------------------------------- /example/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['plugin:@typescript-eslint/recommended', 'plugin:react-hooks/recommended'], 3 | }; 4 | -------------------------------------------------------------------------------- /example/android/app/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/debug.keystore -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | BidirectionalFlatlist Example 3 | 4 | -------------------------------------------------------------------------------- /example/index.tsx: -------------------------------------------------------------------------------- 1 | import { AppRegistry } from 'react-native'; 2 | import App from './src/App'; 3 | 4 | AppRegistry.registerComponent('main', () => App); 5 | -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | // 2 | // Use this file to import your target's public headers that you would like to expose to Swift. 3 | // 4 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version 4 | ruby '2.7.4' 5 | 6 | gem 'cocoapods', '~> 1.11', '>= 1.11.2' 7 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steuerbot/react-native-bidirectional-flatlist/HEAD/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/react-native.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | dependencies: { 5 | 'react-native-bidirectional-flatlist': { 6 | root: path.join(__dirname, '..'), 7 | }, 8 | }, 9 | }; 10 | -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | BidirectionalFlatlist_kotlinVersion=1.7.0 2 | BidirectionalFlatlist_minSdkVersion=21 3 | BidirectionalFlatlist_targetSdkVersion=31 4 | BidirectionalFlatlist_compileSdkVersion=31 5 | BidirectionalFlatlist_ndkversion=21.4.7075529 6 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample/AppDelegate.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | @interface AppDelegate : UIResponder 5 | 6 | @property (nonatomic, strong) UIWindow *window; 7 | 8 | @end 9 | -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample/main.m: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #import "AppDelegate.h" 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | @autoreleasepool { 8 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | indent_style = space 10 | indent_size = 2 11 | 12 | end_of_line = lf 13 | charset = utf-8 14 | trim_trailing_whitespace = true 15 | insert_final_newline = true 16 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /lefthook.yml: -------------------------------------------------------------------------------- 1 | pre-commit: 2 | parallel: true 3 | commands: 4 | lint: 5 | files: git diff --name-only @{push} 6 | glob: "*.{js,ts,jsx,tsx}" 7 | run: npx eslint {files} 8 | types: 9 | files: git diff --name-only @{push} 10 | glob: "*.{js,ts, jsx, tsx}" 11 | run: npx tsc --noEmit 12 | commit-msg: 13 | parallel: true 14 | commands: 15 | commitlint: 16 | run: npx commitlint --edit 17 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/MainApplicationModuleProvider.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | 8 | namespace facebook { 9 | namespace react { 10 | 11 | std::shared_ptr MainApplicationModuleProvider( 12 | const std::string moduleName, 13 | const JavaTurboModule::InitParams ¶ms); 14 | 15 | } // namespace react 16 | } // namespace facebook 17 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/OnLoad.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "MainApplicationTurboModuleManagerDelegate.h" 3 | #include "MainComponentsRegistry.h" 4 | 5 | JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { 6 | return facebook::jni::initialize(vm, [] { 7 | facebook::react::MainApplicationTurboModuleManagerDelegate:: 8 | registerNatives(); 9 | facebook::react::MainComponentsRegistry::registerNatives(); 10 | }); 11 | } 12 | -------------------------------------------------------------------------------- /example/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'BidirectionalFlatlistExample' 2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) 3 | include ':app' 4 | includeBuild('../node_modules/react-native-gradle-plugin') 5 | 6 | if (settings.hasProperty("newArchEnabled") && settings.newArchEnabled == "true") { 7 | include(":ReactAndroid") 8 | project(":ReactAndroid").projectDir = file('../node_modules/react-native/ReactAndroid') 9 | } 10 | -------------------------------------------------------------------------------- /example/babel.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-var-requires */ 2 | const path = require('path'); 3 | const pak = require('../package.json'); 4 | 5 | module.exports = { 6 | presets: ['module:metro-react-native-babel-preset'], 7 | plugins: [ 8 | [ 9 | 'module-resolver', 10 | { 11 | extensions: ['.tsx', '.ts', '.js', '.json'], 12 | alias: { 13 | [pak.name]: path.join(__dirname, '..', pak.source), 14 | }, 15 | }, 16 | ], 17 | 'react-native-reanimated/plugin', 18 | ], 19 | }; 20 | -------------------------------------------------------------------------------- /example/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | -keep class com.facebook.hermes.unicode.** { *; } 13 | -keep class com.facebook.jni.** { *; } 14 | -------------------------------------------------------------------------------- /example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import type { ReactNode } from 'react'; 2 | import type { FlatList as FlatListRN, FlatListProps } from 'react-native'; 3 | 4 | export type RenderItem = (options: {item: T; prerendering?: boolean}) => ReactNode; 5 | export type OnUpdateData = (options: {heights: Record; offset: number; height: number}) => void; 6 | 7 | export type ShiftFunction = ({ offset, height }: { offset: number; height: number }) => void; 8 | 9 | export type FlatListType = typeof FlatListRN & {shift: ShiftFunction}; 10 | 11 | export type KeyExtractor = (item: T) => string; 12 | 13 | export type BidirectionalFlatListProps = FlatListProps & {renderItem: RenderItem, onUpdateData?: OnUpdateData, keyExtractor: KeyExtractor}; 14 | 15 | 16 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-bidirectional-flatlist-example", 3 | "description": "Example app for react-native-bidirectional-flatlist", 4 | "version": "0.0.1", 5 | "private": true, 6 | "scripts": { 7 | "android": "react-native run-android", 8 | "ios": "react-native run-ios", 9 | "start": "react-native start", 10 | "pods": "pod-install --quiet", 11 | "postinstall": "patch-package" 12 | }, 13 | "dependencies": { 14 | "react": "17.0.2", 15 | "react-native": "0.68.2", 16 | "react-native-reanimated": "2.10.0" 17 | }, 18 | "devDependencies": { 19 | "@babel/core": "^7.12.10", 20 | "@babel/runtime": "^7.12.5", 21 | "babel-plugin-module-resolver": "^4.1.0", 22 | "metro-react-native-babel-preset": "^0.67.0", 23 | "patch-package": "^6.4.7", 24 | "postinstall-postinstall": "^2.1.0" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "./", 4 | "paths": { 5 | "react-native-bidirectional-flatlist": ["./src/index"] 6 | }, 7 | "allowUnreachableCode": false, 8 | "allowUnusedLabels": false, 9 | "esModuleInterop": true, 10 | "importsNotUsedAsValues": "error", 11 | "forceConsistentCasingInFileNames": true, 12 | "jsx": "react", 13 | "lib": ["esnext"], 14 | "module": "esnext", 15 | "moduleResolution": "node", 16 | "noFallthroughCasesInSwitch": true, 17 | "noImplicitReturns": true, 18 | "noImplicitUseStrict": false, 19 | "noStrictGenericChecks": false, 20 | "noUncheckedIndexedAccess": true, 21 | "noUnusedLocals": true, 22 | "noUnusedParameters": true, 23 | "resolveJsonModule": true, 24 | "skipLibCheck": true, 25 | "strict": true, 26 | "target": "esnext" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativebidirectionalflatlist/BidirectionalFlatlistPackage.java: -------------------------------------------------------------------------------- 1 | package com.reactnativebidirectionalflatlist; 2 | 3 | import com.facebook.react.ReactPackage; 4 | import com.facebook.react.bridge.NativeModule; 5 | import com.facebook.react.bridge.ReactApplicationContext; 6 | import com.facebook.react.uimanager.ViewManager; 7 | 8 | import java.util.Arrays; 9 | import java.util.Collections; 10 | import java.util.List; 11 | 12 | public class BidirectionalFlatlistPackage implements ReactPackage { 13 | @Override 14 | public List createNativeModules(ReactApplicationContext reactContext) { 15 | return Collections.emptyList(); 16 | } 17 | 18 | @Override 19 | public List createViewManagers(ReactApplicationContext reactContext) { 20 | return Arrays.asList(new BidirectionalFlatlistManager()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /scripts/bootstrap.js: -------------------------------------------------------------------------------- 1 | const os = require('os'); 2 | const path = require('path'); 3 | const child_process = require('child_process'); 4 | 5 | const root = path.resolve(__dirname, '..'); 6 | const args = process.argv.slice(2); 7 | const options = { 8 | cwd: process.cwd(), 9 | env: process.env, 10 | stdio: 'inherit', 11 | encoding: 'utf-8', 12 | }; 13 | 14 | if (os.type() === 'Windows_NT') { 15 | options.shell = true; 16 | } 17 | 18 | let result; 19 | 20 | if (process.cwd() !== root || args.length) { 21 | // We're not in the root of the project, or additional arguments were passed 22 | // In this case, forward the command to `yarn` 23 | result = child_process.spawnSync('yarn', args, options); 24 | } else { 25 | // If `yarn` is run without arguments, perform bootstrap 26 | result = child_process.spawnSync('yarn', ['bootstrap'], options); 27 | } 28 | 29 | process.exitCode = result.status; 30 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/MainApplicationModuleProvider.cpp: -------------------------------------------------------------------------------- 1 | #include "MainApplicationModuleProvider.h" 2 | 3 | #include 4 | 5 | namespace facebook { 6 | namespace react { 7 | 8 | std::shared_ptr MainApplicationModuleProvider( 9 | const std::string moduleName, 10 | const JavaTurboModule::InitParams ¶ms) { 11 | // Here you can provide your own module provider for TurboModules coming from 12 | // either your application or from external libraries. The approach to follow 13 | // is similar to the following (for a library called `samplelibrary`: 14 | // 15 | // auto module = samplelibrary_ModuleProvider(moduleName, params); 16 | // if (module != nullptr) { 17 | // return module; 18 | // } 19 | // return rncore_ModuleProvider(moduleName, params); 20 | 21 | 22 | return rncore_ModuleProvider(moduleName, params); 23 | } 24 | 25 | } // namespace react 26 | } // namespace facebook 27 | -------------------------------------------------------------------------------- /src/BidirectionalFlatlist.ts: -------------------------------------------------------------------------------- 1 | import type { ReactNode } from 'react'; 2 | import { Platform, requireNativeComponent, UIManager, ViewStyle } from 'react-native'; 3 | 4 | const LINKING_ERROR = 5 | `The package 'react-native-bidirectional-flatlist' doesn't seem to be linked. Make sure: \n\n` + 6 | Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) + 7 | '- You rebuilt the app after installing the package\n' + 8 | '- You are not using Expo managed workflow\n'; 9 | 10 | type BidirectionalFlatlistProps = { 11 | style: ViewStyle; 12 | children: ReactNode; 13 | }; 14 | 15 | const ComponentName = 'BidirectionalFlatlist'; 16 | 17 | export const BidirectionalFlatlist = Platform.OS === 'android' ? 18 | UIManager.getViewManagerConfig(ComponentName) != null 19 | ? requireNativeComponent(ComponentName) 20 | : () => { 21 | throw new Error(LINKING_ERROR); 22 | } 23 | : null; 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # XDE 6 | .expo/ 7 | 8 | # VSCode 9 | .vscode/ 10 | jsconfig.json 11 | 12 | # Xcode 13 | # 14 | build/ 15 | *.pbxuser 16 | !default.pbxuser 17 | *.mode1v3 18 | !default.mode1v3 19 | *.mode2v3 20 | !default.mode2v3 21 | *.perspectivev3 22 | !default.perspectivev3 23 | xcuserdata 24 | *.xccheckout 25 | *.moved-aside 26 | DerivedData 27 | *.hmap 28 | *.ipa 29 | *.xcuserstate 30 | project.xcworkspace 31 | 32 | # Android/IJ 33 | # 34 | .classpath 35 | .cxx 36 | .gradle 37 | .idea 38 | .project 39 | .settings 40 | local.properties 41 | android.iml 42 | 43 | # Cocoapods 44 | # 45 | example/ios/Pods 46 | 47 | # Ruby 48 | example/vendor/ 49 | 50 | # node.js 51 | # 52 | node_modules/ 53 | npm-debug.log 54 | yarn-debug.log 55 | yarn-error.log 56 | 57 | # BUCK 58 | buck-out/ 59 | \.buckd/ 60 | android/app/libs 61 | android/keystores/debug.keystore 62 | 63 | # Expo 64 | .expo/* 65 | 66 | # generated by bob 67 | lib/ 68 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/MainComponentsRegistry.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | namespace facebook { 9 | namespace react { 10 | 11 | class MainComponentsRegistry 12 | : public facebook::jni::HybridClass { 13 | public: 14 | // Adapt it to the package you used for your Java class. 15 | constexpr static auto kJavaDescriptor = 16 | "Lcom/example/reactnativebidirectionalflatlist/newarchitecture/components/MainComponentsRegistry;"; 17 | 18 | static void registerNatives(); 19 | 20 | MainComponentsRegistry(ComponentFactory *delegate); 21 | 22 | private: 23 | static std::shared_ptr 24 | sharedProviderRegistry(); 25 | 26 | static jni::local_ref initHybrid( 27 | jni::alias_ref, 28 | ComponentFactory *delegate); 29 | }; 30 | 31 | } // namespace react 32 | } // namespace facebook 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 friedolin 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. 21 | -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 13 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "scale" : "2x", 6 | "size" : "20x20" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "scale" : "3x", 11 | "size" : "20x20" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "scale" : "2x", 16 | "size" : "29x29" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "scale" : "3x", 21 | "size" : "29x29" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "scale" : "2x", 26 | "size" : "40x40" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "scale" : "3x", 31 | "size" : "40x40" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "scale" : "2x", 36 | "size" : "60x60" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "scale" : "3x", 41 | "size" : "60x60" 42 | }, 43 | { 44 | "idiom" : "ios-marketing", 45 | "scale" : "1x", 46 | "size" : "1024x1024" 47 | } 48 | ], 49 | "info" : { 50 | "author" : "xcode", 51 | "version" : 1 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /example/ios/Podfile: -------------------------------------------------------------------------------- 1 | require_relative '../node_modules/react-native/scripts/react_native_pods' 2 | require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' 3 | 4 | platform :ios, '11.0' 5 | install! 'cocoapods', :deterministic_uuids => false 6 | 7 | ENV['RCT_NEW_ARCH_ENABLED'] = '0' 8 | 9 | target 'BidirectionalFlatlistExample' do 10 | config = use_native_modules! 11 | 12 | # Flags change depending on the env values. 13 | flags = get_default_flags() 14 | 15 | use_react_native!( 16 | :path => config[:reactNativePath], 17 | # to enable hermes on iOS, change `false` to `true` and then install pods 18 | :hermes_enabled => true, 19 | :fabric_enabled => flags[:fabric_enabled], 20 | # An absolute path to your application root. 21 | :app_path => "#{Pod::Config.instance.installation_root}/.." 22 | ) 23 | 24 | # Enables Flipper. 25 | # 26 | # Note that if you have use_frameworks! enabled, Flipper will not work and 27 | # you should disable the next line. 28 | use_flipper!() 29 | 30 | post_install do |installer| 31 | react_native_post_install(installer) 32 | __apply_Xcode_12_5_M1_post_install_workaround(installer) 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /example/metro.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const escape = require('escape-string-regexp'); 3 | const exclusionList = require('metro-config/src/defaults/exclusionList'); 4 | const pak = require('../package.json'); 5 | 6 | const root = path.resolve(__dirname, '..'); 7 | 8 | const modules = Object.keys({ 9 | ...pak.peerDependencies, 10 | }); 11 | 12 | module.exports = { 13 | projectRoot: __dirname, 14 | watchFolders: [root], 15 | 16 | // We need to make sure that only one version is loaded for peerDependencies 17 | // So we block them at the root, and alias them to the versions in example's node_modules 18 | resolver: { 19 | blacklistRE: exclusionList( 20 | modules.map( 21 | (m) => 22 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) 23 | ) 24 | ), 25 | 26 | extraNodeModules: modules.reduce((acc, name) => { 27 | acc[name] = path.join(__dirname, 'node_modules', name); 28 | return acc; 29 | }, {}), 30 | }, 31 | 32 | transformer: { 33 | getTransformOptions: async () => ({ 34 | transform: { 35 | experimentalImportSupport: false, 36 | inlineRequires: true, 37 | }, 38 | }), 39 | }, 40 | }; 41 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativebidirectionalflatlist/BidirectionalFlatlistManager.java: -------------------------------------------------------------------------------- 1 | package com.reactnativebidirectionalflatlist; 2 | 3 | import androidx.annotation.NonNull; 4 | 5 | import com.facebook.react.uimanager.ThemedReactContext; 6 | import com.facebook.react.uimanager.annotations.ReactProp; 7 | import com.facebook.react.views.scroll.ReactScrollViewManager; 8 | import com.reactnativebidirectionalflatlist.scroll.ScrollView; 9 | 10 | public class BidirectionalFlatlistManager extends ReactScrollViewManager { 11 | public static final String REACT_CLASS = "BidirectionalFlatlist"; 12 | 13 | @Override 14 | @NonNull 15 | public String getName() { 16 | return REACT_CLASS; 17 | } 18 | 19 | @Override 20 | @NonNull 21 | public ScrollView createViewInstance(ThemedReactContext reactContext) { 22 | return new ScrollView(reactContext); 23 | } 24 | 25 | @ReactProp(name = "shiftHeight") 26 | public void setShiftHeight(ScrollView view, double shiftHeight) { 27 | view.setShiftHeight(shiftHeight); 28 | } 29 | 30 | @ReactProp(name = "shiftOffset") 31 | public void setShiftOffset(ScrollView view, double shiftOffset) { 32 | view.setShiftOffset(shiftOffset); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | #include 6 | 7 | namespace facebook { 8 | namespace react { 9 | 10 | class MainApplicationTurboModuleManagerDelegate 11 | : public jni::HybridClass< 12 | MainApplicationTurboModuleManagerDelegate, 13 | TurboModuleManagerDelegate> { 14 | public: 15 | // Adapt it to the package you used for your Java class. 16 | static constexpr auto kJavaDescriptor = 17 | "Lcom/example/reactnativebidirectionalflatlist/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate;"; 18 | 19 | static jni::local_ref initHybrid(jni::alias_ref); 20 | 21 | static void registerNatives(); 22 | 23 | std::shared_ptr getTurboModule( 24 | const std::string name, 25 | const std::shared_ptr jsInvoker) override; 26 | std::shared_ptr getTurboModule( 27 | const std::string name, 28 | const JavaTurboModule::InitParams ¶ms) override; 29 | 30 | /** 31 | * Test-only method. Allows user to verify whether a TurboModule can be 32 | * created by instances of this class. 33 | */ 34 | bool canCreateTurboModule(std::string name); 35 | }; 36 | 37 | } // namespace react 38 | } // namespace facebook 39 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/example/reactnativebidirectionalflatlist/newarchitecture/components/MainComponentsRegistry.java: -------------------------------------------------------------------------------- 1 | package com.example.reactnativebidirectionalflatlist.newarchitecture.components; 2 | 3 | import com.facebook.jni.HybridData; 4 | import com.facebook.proguard.annotations.DoNotStrip; 5 | import com.facebook.react.fabric.ComponentFactory; 6 | import com.facebook.soloader.SoLoader; 7 | 8 | /** 9 | * Class responsible to load the custom Fabric Components. This class has native methods and needs a 10 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/ 11 | * folder for you). 12 | * 13 | *

Please note that this class is used ONLY if you opt-in for the New Architecture (see the 14 | * `newArchEnabled` property). Is ignored otherwise. 15 | */ 16 | @DoNotStrip 17 | public class MainComponentsRegistry { 18 | static { 19 | SoLoader.loadLibrary("fabricjni"); 20 | } 21 | 22 | @DoNotStrip private final HybridData mHybridData; 23 | 24 | @DoNotStrip 25 | private native HybridData initHybrid(ComponentFactory componentFactory); 26 | 27 | @DoNotStrip 28 | private MainComponentsRegistry(ComponentFactory componentFactory) { 29 | mHybridData = initHybrid(componentFactory); 30 | } 31 | 32 | @DoNotStrip 33 | public static MainComponentsRegistry register(ComponentFactory componentFactory) { 34 | return new MainComponentsRegistry(componentFactory); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/example/reactnativebidirectionalflatlist/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.reactnativebidirectionalflatlist; 2 | 3 | import com.facebook.react.ReactActivity; 4 | import com.facebook.react.ReactActivityDelegate; 5 | import com.facebook.react.ReactRootView; 6 | 7 | public class MainActivity extends ReactActivity { 8 | 9 | /** 10 | * Returns the name of the main component registered from JavaScript. This is used to schedule 11 | * rendering of the component. 12 | */ 13 | @Override 14 | protected String getMainComponentName() { 15 | return "main"; 16 | } 17 | 18 | /** 19 | * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and 20 | * you can specify the rendered you wish to use (Fabric or the older renderer). 21 | */ 22 | @Override 23 | protected ReactActivityDelegate createReactActivityDelegate() { 24 | return new MainActivityDelegate(this, getMainComponentName()); 25 | } 26 | 27 | public static class MainActivityDelegate extends ReactActivityDelegate { 28 | public MainActivityDelegate(ReactActivity activity, String mainComponentName) { 29 | super(activity, mainComponentName); 30 | } 31 | 32 | @Override 33 | protected ReactRootView createRootView() { 34 | ReactRootView reactRootView = new ReactRootView(getContext()); 35 | // If you opted-in for the New Architecture, we enable the Fabric Renderer. 36 | reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED); 37 | return reactRootView; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.cpp: -------------------------------------------------------------------------------- 1 | #include "MainApplicationTurboModuleManagerDelegate.h" 2 | #include "MainApplicationModuleProvider.h" 3 | 4 | namespace facebook { 5 | namespace react { 6 | 7 | jni::local_ref 8 | MainApplicationTurboModuleManagerDelegate::initHybrid( 9 | jni::alias_ref) { 10 | return makeCxxInstance(); 11 | } 12 | 13 | void MainApplicationTurboModuleManagerDelegate::registerNatives() { 14 | registerHybrid({ 15 | makeNativeMethod( 16 | "initHybrid", MainApplicationTurboModuleManagerDelegate::initHybrid), 17 | makeNativeMethod( 18 | "canCreateTurboModule", 19 | MainApplicationTurboModuleManagerDelegate::canCreateTurboModule), 20 | }); 21 | } 22 | 23 | std::shared_ptr 24 | MainApplicationTurboModuleManagerDelegate::getTurboModule( 25 | const std::string name, 26 | const std::shared_ptr jsInvoker) { 27 | // Not implemented yet: provide pure-C++ NativeModules here. 28 | return nullptr; 29 | } 30 | 31 | std::shared_ptr 32 | MainApplicationTurboModuleManagerDelegate::getTurboModule( 33 | const std::string name, 34 | const JavaTurboModule::InitParams ¶ms) { 35 | return MainApplicationModuleProvider(name, params); 36 | } 37 | 38 | bool MainApplicationTurboModuleManagerDelegate::canCreateTurboModule( 39 | std::string name) { 40 | return getTurboModule(name, nullptr) != nullptr || 41 | getTurboModule(name, {.moduleName = name}) != nullptr; 42 | } 43 | 44 | } // namespace react 45 | } // namespace facebook 46 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/Android.mk: -------------------------------------------------------------------------------- 1 | THIS_DIR := $(call my-dir) 2 | 3 | include $(REACT_ANDROID_DIR)/Android-prebuilt.mk 4 | 5 | # If you wish to add a custom TurboModule or Fabric component in your app you 6 | # will have to include the following autogenerated makefile. 7 | # include $(GENERATED_SRC_DIR)/codegen/jni/Android.mk 8 | include $(CLEAR_VARS) 9 | 10 | LOCAL_PATH := $(THIS_DIR) 11 | 12 | # You can customize the name of your application .so file here. 13 | LOCAL_MODULE := example_appmodules 14 | 15 | LOCAL_C_INCLUDES := $(LOCAL_PATH) 16 | LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) 17 | LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) 18 | 19 | # If you wish to add a custom TurboModule or Fabric component in your app you 20 | # will have to uncomment those lines to include the generated source 21 | # files from the codegen (placed in $(GENERATED_SRC_DIR)/codegen/jni) 22 | # 23 | # LOCAL_C_INCLUDES += $(GENERATED_SRC_DIR)/codegen/jni 24 | # LOCAL_SRC_FILES += $(wildcard $(GENERATED_SRC_DIR)/codegen/jni/*.cpp) 25 | # LOCAL_EXPORT_C_INCLUDES += $(GENERATED_SRC_DIR)/codegen/jni 26 | 27 | # Here you should add any native library you wish to depend on. 28 | LOCAL_SHARED_LIBRARIES := \ 29 | libfabricjni \ 30 | libfbjni \ 31 | libfolly_futures \ 32 | libfolly_json \ 33 | libglog \ 34 | libjsi \ 35 | libreact_codegen_rncore \ 36 | libreact_debug \ 37 | libreact_nativemodule_core \ 38 | libreact_render_componentregistry \ 39 | libreact_render_core \ 40 | libreact_render_debug \ 41 | libreact_render_graphics \ 42 | librrc_view \ 43 | libruntimeexecutor \ 44 | libturbomodulejsijni \ 45 | libyoga 46 | 47 | LOCAL_CFLAGS := -DLOG_TAG=\"ReactNative\" -fexceptions -frtti -std=c++17 -Wall 48 | 49 | include $(BUILD_SHARED_LIBRARY) 50 | -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | example 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSRequiresIPhoneOS 26 | 27 | NSAppTransportSecurity 28 | 29 | NSExceptionDomains 30 | 31 | localhost 32 | 33 | NSExceptionAllowsInsecureHTTPLoads 34 | 35 | 36 | 37 | 38 | NSLocationWhenInUseUsageDescription 39 | 40 | UILaunchStoryboardName 41 | LaunchScreen 42 | UIRequiredDeviceCapabilities 43 | 44 | armv7 45 | 46 | UISupportedInterfaceOrientations 47 | 48 | UIInterfaceOrientationPortrait 49 | UIInterfaceOrientationLandscapeLeft 50 | UIInterfaceOrientationLandscapeRight 51 | 52 | UIViewControllerBasedStatusBarAppearance 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m 13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | # AndroidX package structure to make it clearer which packages are bundled with the 21 | # Android operating system, and which are packaged with your app's APK 22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 23 | android.useAndroidX=true 24 | # Automatically convert third-party libraries to use AndroidX 25 | android.enableJetifier=true 26 | 27 | # Version of flipper SDK to use with React Native 28 | FLIPPER_VERSION=0.125.0 29 | 30 | # Use this property to specify which architecture you want to build. 31 | # You can also override it from the CLI using 32 | # ./gradlew -PreactNativeArchitectures=x86_64 33 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 34 | 35 | # Use this property to enable support to the new architecture. 36 | # This will allow you to use TurboModules and the Fabric render in 37 | # your application. You should enable this flag either if you want 38 | # to write custom TurboModules/Fabric components OR use libraries that 39 | # are providing them. 40 | newArchEnabled=false -------------------------------------------------------------------------------- /example/android/build.gradle: -------------------------------------------------------------------------------- 1 | import org.apache.tools.ant.taskdefs.condition.Os 2 | 3 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 4 | 5 | buildscript { 6 | ext { 7 | buildToolsVersion = "31.0.0" 8 | minSdkVersion = 21 9 | compileSdkVersion = 31 10 | targetSdkVersion = 31 11 | 12 | if (System.properties['os.arch'] == "aarch64") { 13 | // For M1 Users we need to use the NDK 24 which added support for aarch64 14 | ndkVersion = "24.0.8215888" 15 | } else { 16 | // Otherwise we default to the side-by-side NDK version from AGP. 17 | ndkVersion = "21.4.7075529" 18 | } 19 | } 20 | repositories { 21 | google() 22 | mavenCentral() 23 | } 24 | dependencies { 25 | classpath("com.android.tools.build:gradle:7.0.4") 26 | classpath("com.facebook.react:react-native-gradle-plugin") 27 | classpath("de.undercouch:gradle-download-task:4.1.2") 28 | // NOTE: Do not place your application dependencies here; they belong 29 | // in the individual module build.gradle files 30 | } 31 | } 32 | 33 | allprojects { 34 | repositories { 35 | maven { 36 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 37 | url("$rootDir/../node_modules/react-native/android") 38 | } 39 | maven { 40 | // Android JSC is installed from npm 41 | url("$rootDir/../node_modules/jsc-android/dist") 42 | } 43 | mavenCentral { 44 | // We don't want to fetch react-native from Maven Central as there are 45 | // older versions over there. 46 | content { 47 | excludeGroup "com.facebook.react" 48 | } 49 | } 50 | google() 51 | maven { url 'https://www.jitpack.io' } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable/rn_edit_text_material.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 21 | 22 | 23 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/example/reactnativebidirectionalflatlist/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java: -------------------------------------------------------------------------------- 1 | package com.example.reactnativebidirectionalflatlist.newarchitecture.modules; 2 | 3 | import com.facebook.jni.HybridData; 4 | import com.facebook.react.ReactPackage; 5 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate; 6 | import com.facebook.react.bridge.ReactApplicationContext; 7 | import com.facebook.soloader.SoLoader; 8 | import java.util.List; 9 | 10 | /** 11 | * Class responsible to load the TurboModules. This class has native methods and needs a 12 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/ 13 | * folder for you). 14 | * 15 | *

Please note that this class is used ONLY if you opt-in for the New Architecture (see the 16 | * `newArchEnabled` property). Is ignored otherwise. 17 | */ 18 | public class MainApplicationTurboModuleManagerDelegate 19 | extends ReactPackageTurboModuleManagerDelegate { 20 | 21 | private static volatile boolean sIsSoLibraryLoaded; 22 | 23 | protected MainApplicationTurboModuleManagerDelegate( 24 | ReactApplicationContext reactApplicationContext, List packages) { 25 | super(reactApplicationContext, packages); 26 | } 27 | 28 | protected native HybridData initHybrid(); 29 | 30 | native boolean canCreateTurboModule(String moduleName); 31 | 32 | public static class Builder extends ReactPackageTurboModuleManagerDelegate.Builder { 33 | protected MainApplicationTurboModuleManagerDelegate build( 34 | ReactApplicationContext context, List packages) { 35 | return new MainApplicationTurboModuleManagerDelegate(context, packages); 36 | } 37 | } 38 | 39 | @Override 40 | protected synchronized void maybeLoadOtherSoLibraries() { 41 | if (!sIsSoLibraryLoaded) { 42 | // If you change the name of your application .so file in the Android.mk file, 43 | // make sure you update the name here as well. 44 | SoLoader.loadLibrary("example_appmodules"); 45 | sIsSoLibraryLoaded = true; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/MainComponentsRegistry.cpp: -------------------------------------------------------------------------------- 1 | #include "MainComponentsRegistry.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | namespace facebook { 9 | namespace react { 10 | 11 | MainComponentsRegistry::MainComponentsRegistry(ComponentFactory *delegate) {} 12 | 13 | std::shared_ptr 14 | MainComponentsRegistry::sharedProviderRegistry() { 15 | auto providerRegistry = CoreComponentsRegistry::sharedProviderRegistry(); 16 | 17 | // Custom Fabric Components go here. You can register custom 18 | // components coming from your App or from 3rd party libraries here. 19 | // 20 | // providerRegistry->add(concreteComponentDescriptorProvider< 21 | // AocViewerComponentDescriptor>()); 22 | return providerRegistry; 23 | } 24 | 25 | jni::local_ref 26 | MainComponentsRegistry::initHybrid( 27 | jni::alias_ref, 28 | ComponentFactory *delegate) { 29 | auto instance = makeCxxInstance(delegate); 30 | 31 | auto buildRegistryFunction = 32 | [](EventDispatcher::Weak const &eventDispatcher, 33 | ContextContainer::Shared const &contextContainer) 34 | -> ComponentDescriptorRegistry::Shared { 35 | auto registry = MainComponentsRegistry::sharedProviderRegistry() 36 | ->createComponentDescriptorRegistry( 37 | {eventDispatcher, contextContainer}); 38 | 39 | auto mutableRegistry = 40 | std::const_pointer_cast(registry); 41 | 42 | mutableRegistry->setFallbackComponentDescriptor( 43 | std::make_shared( 44 | ComponentDescriptorParameters{ 45 | eventDispatcher, contextContainer, nullptr})); 46 | 47 | return registry; 48 | }; 49 | 50 | delegate->buildRegistryFunction = buildRegistryFunction; 51 | return instance; 52 | } 53 | 54 | void MainComponentsRegistry::registerNatives() { 55 | registerHybrid({ 56 | makeNativeMethod("initHybrid", MainComponentsRegistry::initHybrid), 57 | }); 58 | } 59 | 60 | } // namespace react 61 | } // namespace facebook 62 | -------------------------------------------------------------------------------- /src/FlatList.tsx: -------------------------------------------------------------------------------- 1 | import React, { forwardRef, MutableRefObject, useCallback, useRef, useState } from 'react'; 2 | import { FlatList as FlatListRN, LayoutChangeEvent, Platform, ScrollViewProps, StyleSheet, View } from 'react-native'; 3 | import { ScrollView } from './ScrollView'; 4 | import { usePrerenderedData } from './hooks/usePrerenderedData'; 5 | import type { BidirectionalFlatListProps, FlatListType } from './types'; 6 | import { MIN_INDEX } from './config'; 7 | 8 | const maintainVisibleContentPosition = { minIndexForVisible: MIN_INDEX }; 9 | 10 | const FlatListImpl = forwardRef((props, ref) => { 11 | const renderScrollComponent = useCallback((props: ScrollViewProps) => { 12 | return ; 13 | }, []); 14 | 15 | const capturedRef = useRef(); 16 | const captureRef = useCallback((r: any) => { 17 | const obj = r ? Object.assign(r, { 18 | shift: (options: {height: number; offset: number}) => { 19 | if(Platform.OS !== 'android') { 20 | return; 21 | } 22 | r.getNativeScrollRef().shift(options); 23 | }, 24 | }) : r; 25 | capturedRef.current = obj; 26 | if(!ref) { 27 | return; 28 | } 29 | if(typeof ref === 'function') { 30 | ref(obj); 31 | } else { 32 | (ref as MutableRefObject).current = obj; 33 | } 34 | }, [ref]); 35 | 36 | // todo add hack to prevent flickering 37 | const { 38 | data = [], 39 | keyExtractor = (item: any) => item.id ?? item.key, 40 | renderItem, 41 | onUpdateData, 42 | getItemLayout, 43 | onLayout, 44 | } = props; 45 | const {finalData, prerender, getItemLayoutCustom} = usePrerenderedData({ 46 | data: data ?? [], 47 | keyExtractor, 48 | renderItem, 49 | scrollRef: capturedRef as MutableRefObject, 50 | onUpdateData, 51 | getItemLayout, 52 | }); 53 | 54 | const [width, setWidth] = useState(); 55 | const onLayoutFlatList = useCallback((e: LayoutChangeEvent) => { 56 | onLayout?.(e); 57 | setWidth(e.nativeEvent.layout.width); 58 | }, [onLayout]); 59 | 60 | return <> 61 | 69 | {prerender && !!width && 70 | {prerender} 71 | } 72 | 73 | }) 74 | 75 | const styles = StyleSheet.create({ 76 | prerender: { 77 | position: 'absolute', 78 | top: 0, 79 | left: -10000, 80 | } 81 | }); 82 | 83 | export const FlatList = FlatListImpl as unknown as FlatListType 84 | -------------------------------------------------------------------------------- /example/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | CFPropertyList (3.0.5) 5 | rexml 6 | activesupport (6.1.5.1) 7 | concurrent-ruby (~> 1.0, >= 1.0.2) 8 | i18n (>= 1.6, < 2) 9 | minitest (>= 5.1) 10 | tzinfo (~> 2.0) 11 | zeitwerk (~> 2.3) 12 | addressable (2.8.0) 13 | public_suffix (>= 2.0.2, < 5.0) 14 | algoliasearch (1.27.5) 15 | httpclient (~> 2.8, >= 2.8.3) 16 | json (>= 1.5.1) 17 | atomos (0.1.3) 18 | claide (1.1.0) 19 | cocoapods (1.11.3) 20 | addressable (~> 2.8) 21 | claide (>= 1.0.2, < 2.0) 22 | cocoapods-core (= 1.11.3) 23 | cocoapods-deintegrate (>= 1.0.3, < 2.0) 24 | cocoapods-downloader (>= 1.4.0, < 2.0) 25 | cocoapods-plugins (>= 1.0.0, < 2.0) 26 | cocoapods-search (>= 1.0.0, < 2.0) 27 | cocoapods-trunk (>= 1.4.0, < 2.0) 28 | cocoapods-try (>= 1.1.0, < 2.0) 29 | colored2 (~> 3.1) 30 | escape (~> 0.0.4) 31 | fourflusher (>= 2.3.0, < 3.0) 32 | gh_inspector (~> 1.0) 33 | molinillo (~> 0.8.0) 34 | nap (~> 1.0) 35 | ruby-macho (>= 1.0, < 3.0) 36 | xcodeproj (>= 1.21.0, < 2.0) 37 | cocoapods-core (1.11.3) 38 | activesupport (>= 5.0, < 7) 39 | addressable (~> 2.8) 40 | algoliasearch (~> 1.0) 41 | concurrent-ruby (~> 1.1) 42 | fuzzy_match (~> 2.0.4) 43 | nap (~> 1.0) 44 | netrc (~> 0.11) 45 | public_suffix (~> 4.0) 46 | typhoeus (~> 1.0) 47 | cocoapods-deintegrate (1.0.5) 48 | cocoapods-downloader (1.6.3) 49 | cocoapods-plugins (1.0.0) 50 | nap 51 | cocoapods-search (1.0.1) 52 | cocoapods-trunk (1.6.0) 53 | nap (>= 0.8, < 2.0) 54 | netrc (~> 0.11) 55 | cocoapods-try (1.2.0) 56 | colored2 (3.1.2) 57 | concurrent-ruby (1.1.10) 58 | escape (0.0.4) 59 | ethon (0.15.0) 60 | ffi (>= 1.15.0) 61 | ffi (1.15.5) 62 | fourflusher (2.3.1) 63 | fuzzy_match (2.0.4) 64 | gh_inspector (1.1.3) 65 | httpclient (2.8.3) 66 | i18n (1.10.0) 67 | concurrent-ruby (~> 1.0) 68 | json (2.6.1) 69 | minitest (5.15.0) 70 | molinillo (0.8.0) 71 | nanaimo (0.3.0) 72 | nap (1.1.0) 73 | netrc (0.11.0) 74 | public_suffix (4.0.7) 75 | rexml (3.2.5) 76 | ruby-macho (2.5.1) 77 | typhoeus (1.4.0) 78 | ethon (>= 0.9.0) 79 | tzinfo (2.0.4) 80 | concurrent-ruby (~> 1.0) 81 | xcodeproj (1.21.0) 82 | CFPropertyList (>= 2.3.3, < 4.0) 83 | atomos (~> 0.1.3) 84 | claide (>= 1.0.2, < 2.0) 85 | colored2 (~> 3.1) 86 | nanaimo (~> 0.3.0) 87 | rexml (~> 3.2.4) 88 | zeitwerk (2.5.4) 89 | 90 | PLATFORMS 91 | ruby 92 | 93 | DEPENDENCIES 94 | cocoapods (~> 1.11, >= 1.11.2) 95 | 96 | RUBY VERSION 97 | ruby 2.7.4p191 98 | 99 | BUNDLED WITH 100 | 2.2.27 101 | -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample.xcodeproj/xcshareddata/xcschemes/BidirectionalFlatlistExample.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 35 | 37 | 43 | 44 | 45 | 46 | 52 | 54 | 60 | 61 | 62 | 63 | 65 | 66 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /example/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/example/reactnativebidirectionalflatlist/MainApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.reactnativebidirectionalflatlist; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | import com.facebook.react.PackageList; 6 | import com.facebook.react.ReactApplication; 7 | import com.facebook.react.ReactInstanceManager; 8 | import com.facebook.react.ReactNativeHost; 9 | import com.facebook.react.ReactPackage; 10 | import com.facebook.react.config.ReactFeatureFlags; 11 | import com.facebook.soloader.SoLoader; 12 | import com.example.reactnativebidirectionalflatlist.newarchitecture.MainApplicationReactNativeHost; 13 | import java.lang.reflect.InvocationTargetException; 14 | import java.util.List; 15 | 16 | public class MainApplication extends Application implements ReactApplication { 17 | 18 | private final ReactNativeHost mReactNativeHost = 19 | new ReactNativeHost(this) { 20 | @Override 21 | public boolean getUseDeveloperSupport() { 22 | return BuildConfig.DEBUG; 23 | } 24 | 25 | @Override 26 | protected List getPackages() { 27 | @SuppressWarnings("UnnecessaryLocalVariable") 28 | List packages = new PackageList(this).getPackages(); 29 | // Packages that cannot be autolinked yet can be added manually here, for example: 30 | // packages.add(new MyReactNativePackage()); 31 | return packages; 32 | } 33 | 34 | @Override 35 | protected String getJSMainModuleName() { 36 | return "index"; 37 | } 38 | }; 39 | 40 | private final ReactNativeHost mNewArchitectureNativeHost = 41 | new MainApplicationReactNativeHost(this); 42 | 43 | @Override 44 | public ReactNativeHost getReactNativeHost() { 45 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { 46 | return mNewArchitectureNativeHost; 47 | } else { 48 | return mReactNativeHost; 49 | } 50 | } 51 | 52 | @Override 53 | public void onCreate() { 54 | super.onCreate(); 55 | // If you opted-in for the New Architecture, we enable the TurboModule system 56 | ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; 57 | SoLoader.init(this, /* native exopackage */ false); 58 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); 59 | } 60 | 61 | /** 62 | * Loads Flipper in React Native templates. Call this in the onCreate method with something like 63 | * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); 64 | * 65 | * @param context 66 | * @param reactInstanceManager 67 | */ 68 | private static void initializeFlipper( 69 | Context context, ReactInstanceManager reactInstanceManager) { 70 | if (BuildConfig.DEBUG) { 71 | try { 72 | /* 73 | We use reflection here to pick up the class that initializes Flipper, 74 | since Flipper library is not available in release mode 75 | */ 76 | Class aClass = Class.forName("com.example.reactnativebidirectionalflatlist.ReactNativeFlipper"); 77 | aClass 78 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) 79 | .invoke(null, context, reactInstanceManager); 80 | } catch (ClassNotFoundException e) { 81 | e.printStackTrace(); 82 | } catch (NoSuchMethodException e) { 83 | e.printStackTrace(); 84 | } catch (IllegalAccessException e) { 85 | e.printStackTrace(); 86 | } catch (InvocationTargetException e) { 87 | e.printStackTrace(); 88 | } 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /example/android/app/src/debug/java/com/example/reactnativebidirectionalflatlist/ReactNativeFlipper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * 4 | *

This source code is licensed under the MIT license found in the LICENSE file in the root 5 | * directory of this source tree. 6 | */ 7 | package com.example.reactnativebidirectionalflatlist; 8 | 9 | import android.content.Context; 10 | import com.facebook.flipper.android.AndroidFlipperClient; 11 | import com.facebook.flipper.android.utils.FlipperUtils; 12 | import com.facebook.flipper.core.FlipperClient; 13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; 14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; 15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; 16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping; 17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; 18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; 19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; 20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin; 21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; 22 | import com.facebook.react.ReactInstanceEventListener; 23 | import com.facebook.react.ReactInstanceManager; 24 | import com.facebook.react.bridge.ReactContext; 25 | import com.facebook.react.modules.network.NetworkingModule; 26 | import okhttp3.OkHttpClient; 27 | 28 | public class ReactNativeFlipper { 29 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { 30 | if (FlipperUtils.shouldEnableFlipper(context)) { 31 | final FlipperClient client = AndroidFlipperClient.getInstance(context); 32 | 33 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); 34 | client.addPlugin(new ReactFlipperPlugin()); 35 | client.addPlugin(new DatabasesFlipperPlugin(context)); 36 | client.addPlugin(new SharedPreferencesFlipperPlugin(context)); 37 | client.addPlugin(CrashReporterPlugin.getInstance()); 38 | 39 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin(); 40 | NetworkingModule.setCustomClientBuilder( 41 | new NetworkingModule.CustomClientBuilder() { 42 | @Override 43 | public void apply(OkHttpClient.Builder builder) { 44 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); 45 | } 46 | }); 47 | client.addPlugin(networkFlipperPlugin); 48 | client.start(); 49 | 50 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized 51 | // Hence we run if after all native modules have been initialized 52 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); 53 | if (reactContext == null) { 54 | reactInstanceManager.addReactInstanceEventListener( 55 | new ReactInstanceEventListener() { 56 | @Override 57 | public void onReactContextInitialized(ReactContext reactContext) { 58 | reactInstanceManager.removeReactInstanceEventListener(this); 59 | reactContext.runOnNativeModulesQueueThread( 60 | new Runnable() { 61 | @Override 62 | public void run() { 63 | client.addPlugin(new FrescoFlipperPlugin()); 64 | } 65 | }); 66 | } 67 | }); 68 | } else { 69 | client.addPlugin(new FrescoFlipperPlugin()); 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | } 6 | 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:3.5.3' 9 | } 10 | } 11 | 12 | def isNewArchitectureEnabled() { 13 | return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true" 14 | } 15 | 16 | apply plugin: 'com.android.library' 17 | 18 | if (isNewArchitectureEnabled()) { 19 | apply plugin: 'com.facebook.react' 20 | } 21 | 22 | def getExtOrDefault(name) { 23 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['BidirectionalFlatlist_' + name] 24 | } 25 | 26 | def getExtOrIntegerDefault(name) { 27 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties['BidirectionalFlatlist_' + name]).toInteger() 28 | } 29 | 30 | android { 31 | compileSdkVersion getExtOrIntegerDefault('compileSdkVersion') 32 | 33 | defaultConfig { 34 | minSdkVersion getExtOrIntegerDefault('minSdkVersion') 35 | targetSdkVersion getExtOrIntegerDefault('targetSdkVersion') 36 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString() 37 | } 38 | buildTypes { 39 | release { 40 | minifyEnabled false 41 | } 42 | } 43 | 44 | lintOptions { 45 | disable 'GradleCompatible' 46 | } 47 | 48 | compileOptions { 49 | sourceCompatibility JavaVersion.VERSION_1_8 50 | targetCompatibility JavaVersion.VERSION_1_8 51 | } 52 | } 53 | 54 | repositories { 55 | mavenCentral() 56 | google() 57 | 58 | def found = false 59 | def defaultDir = null 60 | def androidSourcesName = 'React Native sources' 61 | 62 | if (rootProject.ext.has('reactNativeAndroidRoot')) { 63 | defaultDir = rootProject.ext.get('reactNativeAndroidRoot') 64 | } else { 65 | defaultDir = new File( 66 | projectDir, 67 | '/../../../node_modules/react-native/android' 68 | ) 69 | } 70 | 71 | if (defaultDir.exists()) { 72 | maven { 73 | url defaultDir.toString() 74 | name androidSourcesName 75 | } 76 | 77 | logger.info(":${project.name}:reactNativeAndroidRoot ${defaultDir.canonicalPath}") 78 | found = true 79 | } else { 80 | def parentDir = rootProject.projectDir 81 | 82 | 1.upto(5, { 83 | if (found) return true 84 | parentDir = parentDir.parentFile 85 | 86 | def androidSourcesDir = new File( 87 | parentDir, 88 | 'node_modules/react-native' 89 | ) 90 | 91 | def androidPrebuiltBinaryDir = new File( 92 | parentDir, 93 | 'node_modules/react-native/android' 94 | ) 95 | 96 | if (androidPrebuiltBinaryDir.exists()) { 97 | maven { 98 | url androidPrebuiltBinaryDir.toString() 99 | name androidSourcesName 100 | } 101 | 102 | logger.info(":${project.name}:reactNativeAndroidRoot ${androidPrebuiltBinaryDir.canonicalPath}") 103 | found = true 104 | } else if (androidSourcesDir.exists()) { 105 | maven { 106 | url androidSourcesDir.toString() 107 | name androidSourcesName 108 | } 109 | 110 | logger.info(":${project.name}:reactNativeAndroidRoot ${androidSourcesDir.canonicalPath}") 111 | found = true 112 | } 113 | }) 114 | } 115 | 116 | if (!found) { 117 | throw new GradleException( 118 | "${project.name}: unable to locate React Native android sources. " + 119 | "Ensure you have you installed React Native as a dependency in your project and try again." 120 | ) 121 | } 122 | } 123 | 124 | 125 | dependencies { 126 | //noinspection GradleDynamicVersion 127 | implementation "com.facebook.react:react-native:+" 128 | // From node_modules 129 | } 130 | 131 | if (isNewArchitectureEnabled()) { 132 | react { 133 | jsRootDir = file("../src/") 134 | libraryName = "BidirectionalFlatlist" 135 | codegenJavaPackageName = "com.reactnativebidirectionalflatlist" 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativebidirectionalflatlist/scroll/ScrollView.java: -------------------------------------------------------------------------------- 1 | package com.reactnativebidirectionalflatlist.scroll; 2 | 3 | import android.content.Context; 4 | import android.util.Log; 5 | import android.view.View; 6 | import android.widget.OverScroller; 7 | 8 | import androidx.annotation.Nullable; 9 | import androidx.core.view.ViewCompat; 10 | 11 | import com.facebook.common.logging.FLog; 12 | import com.facebook.react.common.ReactConstants; 13 | import com.facebook.react.views.scroll.ReactScrollView; 14 | 15 | import java.lang.reflect.Field; 16 | 17 | public class ScrollView extends ReactScrollView { 18 | 19 | private OverScroller mScroller; 20 | private boolean mTriedToGetScroller; 21 | protected double mShiftHeight = 0; 22 | protected double mShiftOffset = 0; 23 | 24 | public ScrollView(Context context) { 25 | super(context, null); 26 | } 27 | 28 | public void setShiftHeight(double shiftHeight) { 29 | mShiftHeight = shiftHeight; 30 | Log.d("ScrollView", "set shiftHeight " + shiftHeight); 31 | } 32 | 33 | public void setShiftOffset(double shiftOffset) { 34 | mShiftOffset = shiftOffset; 35 | Log.d("ScrollView", "set shiftOffset " + shiftOffset); 36 | } 37 | 38 | @Override 39 | public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { 40 | super.onLayoutChange(v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom); 41 | int scrollWindowHeight = getHeight() - getPaddingBottom() - getPaddingTop(); 42 | if(mShiftHeight != 0 && mShiftOffset <= getScrollY() + scrollWindowHeight / 2) { 43 | // correct 44 | scrollTo(0, getScrollY() + (int)mShiftHeight); 45 | if(getOverScrollerFromParent() != null && !getOverScrollerFromParent().isFinished()) { 46 | // get current directed velocity from scroller 47 | int direction = getOverScrollerFromParent().getFinalY() - getOverScrollerFromParent().getStartY() > 0 ? 1 : -1; 48 | float velocity = getOverScrollerFromParent().getCurrVelocity() * direction; 49 | // stop and restart animation again 50 | getOverScrollerFromParent().abortAnimation(); 51 | mScroller.fling( 52 | getScrollX(), // startX 53 | getScrollY(), // startY 54 | 0, // velocityX 55 | (int)velocity, // velocityY 56 | 0, // minX 57 | 0, // maxX 58 | 0, // minY 59 | Integer.MAX_VALUE, // maxY 60 | 0, // overX 61 | scrollWindowHeight / 2 // overY 62 | ); 63 | ViewCompat.postInvalidateOnAnimation(this); 64 | } 65 | } 66 | mShiftHeight = 0; 67 | mShiftOffset = 0; 68 | } 69 | 70 | @Nullable 71 | private OverScroller getOverScrollerFromParent() { 72 | if(mTriedToGetScroller) { 73 | return mScroller; 74 | } 75 | mTriedToGetScroller = true; 76 | Field field = null; 77 | try { 78 | field = ReactScrollView.class.getDeclaredField("mScroller"); 79 | field.setAccessible(true); 80 | } catch (NoSuchFieldException e) { 81 | FLog.w( 82 | "ScrollView", 83 | "Failed to get mScroller field for ScrollView! " 84 | + "This app will exhibit the bounce-back scrolling bug :("); 85 | } 86 | 87 | if(field != null) { 88 | Object scrollerValue = null; 89 | try { 90 | scrollerValue = field.get(this); 91 | if (scrollerValue instanceof OverScroller) { 92 | mScroller = (OverScroller) scrollerValue; 93 | } else { 94 | FLog.w( 95 | ReactConstants.TAG, 96 | "Failed to cast mScroller field in ScrollView (probably due to OEM changes to AOSP)! " 97 | + "This app will exhibit the bounce-back scrolling bug :("); 98 | mScroller = null; 99 | } 100 | } catch (IllegalAccessException e) { 101 | throw new RuntimeException("Failed to get mScroller from ScrollView!", e); 102 | } 103 | } 104 | return mScroller; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample/AppDelegate.mm: -------------------------------------------------------------------------------- 1 | #import "AppDelegate.h" 2 | 3 | #import 4 | #import 5 | #import 6 | 7 | #import 8 | 9 | #if RCT_NEW_ARCH_ENABLED 10 | #import 11 | #import 12 | #import 13 | #import 14 | #import 15 | #import 16 | 17 | #import 18 | 19 | @interface AppDelegate () { 20 | RCTTurboModuleManager *_turboModuleManager; 21 | RCTSurfacePresenterBridgeAdapter *_bridgeAdapter; 22 | std::shared_ptr _reactNativeConfig; 23 | facebook::react::ContextContainer::Shared _contextContainer; 24 | } 25 | @end 26 | #endif 27 | 28 | @implementation AppDelegate 29 | 30 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 31 | { 32 | RCTAppSetupPrepareApp(application); 33 | 34 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; 35 | 36 | #if RCT_NEW_ARCH_ENABLED 37 | _contextContainer = std::make_shared(); 38 | _reactNativeConfig = std::make_shared(); 39 | _contextContainer->insert("ReactNativeConfig", _reactNativeConfig); 40 | _bridgeAdapter = [[RCTSurfacePresenterBridgeAdapter alloc] initWithBridge:bridge contextContainer:_contextContainer]; 41 | bridge.surfacePresenter = _bridgeAdapter.surfacePresenter; 42 | #endif 43 | 44 | UIView *rootView = RCTAppSetupDefaultRootView(bridge, @"main", nil); 45 | 46 | if (@available(iOS 13.0, *)) { 47 | rootView.backgroundColor = [UIColor systemBackgroundColor]; 48 | } else { 49 | rootView.backgroundColor = [UIColor whiteColor]; 50 | } 51 | 52 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 53 | UIViewController *rootViewController = [UIViewController new]; 54 | rootViewController.view = rootView; 55 | self.window.rootViewController = rootViewController; 56 | [self.window makeKeyAndVisible]; 57 | return YES; 58 | } 59 | 60 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge 61 | { 62 | #if DEBUG 63 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"]; 64 | #else 65 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; 66 | #endif 67 | } 68 | 69 | #if RCT_NEW_ARCH_ENABLED 70 | 71 | #pragma mark - RCTCxxBridgeDelegate 72 | 73 | - (std::unique_ptr)jsExecutorFactoryForBridge:(RCTBridge *)bridge 74 | { 75 | _turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridge:bridge 76 | delegate:self 77 | jsInvoker:bridge.jsCallInvoker]; 78 | return RCTAppSetupDefaultJsExecutorFactory(bridge, _turboModuleManager); 79 | } 80 | 81 | #pragma mark RCTTurboModuleManagerDelegate 82 | 83 | - (Class)getModuleClassFromName:(const char *)name 84 | { 85 | return RCTCoreModulesClassProvider(name); 86 | } 87 | 88 | - (std::shared_ptr)getTurboModule:(const std::string &)name 89 | jsInvoker:(std::shared_ptr)jsInvoker 90 | { 91 | return nullptr; 92 | } 93 | 94 | - (std::shared_ptr)getTurboModule:(const std::string &)name 95 | initParams: 96 | (const facebook::react::ObjCTurboModule::InitParams &)params 97 | { 98 | return nullptr; 99 | } 100 | 101 | - (id)getModuleInstanceFromClass:(Class)moduleClass 102 | { 103 | return RCTAppSetupDefaultModuleFromClass(moduleClass); 104 | } 105 | 106 | #endif 107 | 108 | @end 109 | -------------------------------------------------------------------------------- /example/ios/BidirectionalFlatlistExample/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 24 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-bidirectional-flatlist", 3 | "version": "0.6.0", 4 | "description": "A FlatList which can handle prepending and appending and still holding the current position", 5 | "main": "lib/commonjs/index", 6 | "module": "lib/module/index", 7 | "types": "lib/typescript/index.d.ts", 8 | "react-native": "src/index", 9 | "source": "src/index", 10 | "files": [ 11 | "src", 12 | "lib", 13 | "android", 14 | "ios", 15 | "cpp", 16 | "react-native-bidirectional-flatlist.podspec", 17 | "!lib/typescript/example", 18 | "!android/build", 19 | "!ios/build", 20 | "!**/__tests__", 21 | "!**/__fixtures__", 22 | "!**/__mocks__" 23 | ], 24 | "scripts": { 25 | "test": "jest", 26 | "typescript": "tsc --noEmit", 27 | "lint": "eslint \"**/*.{js,ts,tsx}\"", 28 | "prepare": "bob build", 29 | "release": "release-it", 30 | "example": "yarn --cwd example", 31 | "bootstrap": "yarn example && yarn && yarn example pods" 32 | }, 33 | "keywords": [ 34 | "react-native", 35 | "ios", 36 | "android" 37 | ], 38 | "repository": "https://github.com/steuerbot/react-native-bidirectional-flatlist", 39 | "author": "Friedolin Förder ", 40 | "license": "MIT", 41 | "bugs": { 42 | "url": "https://github.com/steuerbot/react-native-bidirectional-flatlist/issues" 43 | }, 44 | "homepage": "https://github.com/steuerbot/react-native-bidirectional-flatlist#readme", 45 | "publishConfig": { 46 | "registry": "https://registry.npmjs.org/" 47 | }, 48 | "devDependencies": { 49 | "@arkweid/lefthook": "^0.7.7", 50 | "@babel/eslint-parser": "^7.18.2", 51 | "@commitlint/config-conventional": "^17.0.2", 52 | "@react-native-community/eslint-config": "^3.0.2", 53 | "@release-it/conventional-changelog": "^5.0.0", 54 | "@types/jest": "^28.1.2", 55 | "@types/react": "~17.0.21", 56 | "@types/react-native": "0.68.0", 57 | "commitlint": "^17.0.2", 58 | "eslint": "8.22.0", 59 | "eslint-config-prettier": "^8.5.0", 60 | "eslint-plugin-prettier": "^4.0.0", 61 | "eslint-plugin-react-hooks": "4.6.0", 62 | "jest": "^28.1.1", 63 | "pod-install": "^0.1.0", 64 | "prettier": "^2.0.5", 65 | "react": "17.0.2", 66 | "react-native": "0.68.2", 67 | "react-native-builder-bob": "^0.18.3", 68 | "release-it": "^15.0.0", 69 | "typescript": "^4.5.2" 70 | }, 71 | "resolutions": { 72 | "@types/react": "17.0.21" 73 | }, 74 | "peerDependencies": { 75 | "react": "*", 76 | "react-native": "*" 77 | }, 78 | "jest": { 79 | "preset": "react-native", 80 | "modulePathIgnorePatterns": [ 81 | "/example/node_modules", 82 | "/lib/" 83 | ] 84 | }, 85 | "commitlint": { 86 | "extends": [ 87 | "@commitlint/config-conventional" 88 | ] 89 | }, 90 | "release-it": { 91 | "git": { 92 | "commitMessage": "chore: release ${version}", 93 | "tagName": "v${version}" 94 | }, 95 | "npm": { 96 | "publish": true 97 | }, 98 | "github": { 99 | "release": true 100 | }, 101 | "plugins": { 102 | "@release-it/conventional-changelog": { 103 | "preset": "angular" 104 | } 105 | } 106 | }, 107 | "eslintConfig": { 108 | "root": true, 109 | "parser": "@babel/eslint-parser", 110 | "extends": [ 111 | "@react-native-community", 112 | "prettier" 113 | ], 114 | "rules": { 115 | "prettier/prettier": [ 116 | "error", 117 | { 118 | "quoteProps": "consistent", 119 | "singleQuote": true, 120 | "tabWidth": 2, 121 | "trailingComma": "es5", 122 | "useTabs": false 123 | } 124 | ] 125 | } 126 | }, 127 | "eslintIgnore": [ 128 | "node_modules/", 129 | "lib/" 130 | ], 131 | "prettier": { 132 | "quoteProps": "consistent", 133 | "singleQuote": true, 134 | "tabWidth": 2, 135 | "trailingComma": "es5", 136 | "useTabs": false 137 | }, 138 | "react-native-builder-bob": { 139 | "source": "src", 140 | "output": "lib", 141 | "targets": [ 142 | "commonjs", 143 | "module", 144 | [ 145 | "typescript", 146 | { 147 | "project": "tsconfig.build.json" 148 | } 149 | ] 150 | ] 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-native-bidirectional-flatlist 2 | [![npm version](https://img.shields.io/npm/v/react-native-bidirectional-flatlist.svg?style=flat)](https://www.npmjs.com/package/react-native-bidirectional-flatlist) 3 | [![License](https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) 4 | 5 | A FlatList replacement which uses the official React Native Implementation of FlatList and adds [Item height calculation](#item-height-calculation) of list items and [correction of the current scroll position](#adjust-the-current-scroll-position) on top of it. 6 | Tested with React Native 0.69 (for RN < 0.68 see [Troubleshooting](#troubleshooting)) 7 | 8 | ## How is it done 9 | 10 | ### Item height calculation 11 | Whenever a new list item is added to the list, the height of this new item is calculated outside of the viewport and will be used later on in the `getItemLayout` function. You can skip this step by providing your own implementation / function of `getItemLayout`. 12 | 13 | ### Adjust the current scroll position 14 | When items will be prepended, the heights of the new items will be used to correct the current scroll position of the FlatList. The correction is made in the native part of the ScrollView component. 15 | For iOS, this is not necessary, because the property `maintainVisibleContentPosition` will be used. 16 | 17 | ## React Native Versions 18 | 19 | | react-native | react-native-bidirectional-flatlist | 20 | |-----------------|-------------------------------------| 21 | | 0.73.x | 0.6.0 | 22 | | 0.72.x | ? (untested) | 23 | | 0.71.x – 0.69.x | 0.5.0 | 24 | 25 | ## Examples 26 | 27 | ### Prepend items during scroll 28 | ![Prepend items](./docu/prepend.gif) 29 | 30 | ### Remove one item and prepend multiple 31 | ![Remove one and prepend multiple](./docu/remove-and-add.gif) 32 | 33 | ## Installation 34 | 35 | ```sh 36 | npm install react-native-bidirectional-flatlist 37 | ``` 38 | 39 | or 40 | 41 | ```sh 42 | yarn add react-native-bidirectional-flatlist 43 | ``` 44 | 45 | ## Usage 46 | 47 | ```js 48 | import BidirectionalFlatlist from "react-native-bidirectional-flatlist"; 49 | 50 | // ... 51 | 52 | 53 | ``` 54 | 55 | ### Properties 56 | | Name | description | required | default | 57 | |---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------|---------| 58 | | data | The data array, see [RN doc](https://reactnative.dev/docs/flatlist#required-data) | ☑️ | | 59 | | renderItem | Render function, see [RN doc](https://reactnative.dev/docs/flatlist#required-renderitem). Difference to FlatList: Argument is {item: T; prerendering: boolean} | ☑️ | | 60 | | keyExtractor | Function, which returns the key / id of the item, see [RN doc](https://reactnative.dev/docs/flatlist#keyextractor). Difference to FlatList: The index-Parameter is missing | | (item) => item.id ?? item.key | 61 | | getItemLayout | If you know the dimensions of the items you can provide it, otherwise prerendering would be used to determine the height. See [RN doc](https://reactnative.dev/docs/flatlist#getitemlayout) | | | 62 | |...|||| 63 | 64 | Separators are not allowed. For other properties see [RN doc](https://reactnative.dev/docs/flatlist). 65 | 66 | ## Typescript 67 | 68 | Built with Typescript, so works with Typescript out of the box. 69 | 70 | ## Contributing 71 | 72 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. 73 | 74 | ## Troubleshooting 75 | 76 | If you use React Native Version < 0.68.0 the constructor of ReactScrollView is different and therefore you get a crash on Android. 77 | You can change (e.g. with [patch-package](https://github.com/ds300/patch-package)) the constructor like so: 78 | ``` 79 | import com.facebook.react.bridge.ReactContext; 80 | ... 81 | 82 | public ScrollView(ReactContext context) { 83 | super(context, null); 84 | } 85 | ``` 86 | 87 | ## License 88 | 89 | **[MIT](https://github.com/steuerbot/react-native-bidirectional-flatlist/blob/main/LICENSE)** 90 | -------------------------------------------------------------------------------- /src/hooks/usePrerenderedData.tsx: -------------------------------------------------------------------------------- 1 | import React, { MutableRefObject, ReactNode, useCallback, useEffect, useRef, useState } from 'react'; 2 | import { FlatListProps, LayoutChangeEvent, View } from 'react-native'; 3 | import type { FlatListType, KeyExtractor, OnUpdateData, RenderItem } from '../types'; 4 | import { MIN_INDEX } from '../config'; 5 | 6 | type OnLayout = (options: {id: string; height: number}) => void; 7 | 8 | const Prerender = ({id, onLayout, children}: {id: string; onLayout: OnLayout; children: ReactNode}) => { 9 | const onLayoutView = useCallback((e: LayoutChangeEvent) => { 10 | onLayout({ 11 | id, 12 | height: e.nativeEvent.layout.height, 13 | }); 14 | }, [id, onLayout]); 15 | 16 | return 17 | {children} 18 | 19 | } 20 | 21 | export const usePrerenderedData = ({data, keyExtractor, renderItem, scrollRef, onUpdateData, getItemLayout}: { 22 | data: readonly any[]; 23 | keyExtractor: KeyExtractor; 24 | renderItem: RenderItem 25 | scrollRef: MutableRefObject; 26 | onUpdateData?: OnUpdateData; 27 | getItemLayout?: FlatListProps['getItemLayout']; 28 | }) => { 29 | const [finalData, setFinalData] = useState([]); 30 | const [newData, setNewData] = useState([]); 31 | 32 | const heightsRef = useRef>({}); 33 | const getHeight = useCallback((list: any[], heights= heightsRef.current) => { 34 | return list.reduce((p, c) => p + heights[keyExtractor(c)], 0) 35 | }, [keyExtractor]); 36 | 37 | const shift = useCallback((newData: any[], oldHeights: Record) => { 38 | const removedData = []; 39 | for (const d of finalData) { 40 | if(!heightsRef.current[keyExtractor(d)]) { 41 | removedData.push(d); 42 | } else { 43 | break; 44 | } 45 | } 46 | 47 | const shiftValue = { 48 | height: -getHeight(removedData, oldHeights), 49 | offset: 0, 50 | }; 51 | const index = data.findIndex((d) => d === newData[0]); 52 | if(index >= 0 && index <= MIN_INDEX) { 53 | shiftValue.height += getHeight(newData); 54 | shiftValue.offset = getHeight(data.slice(0, index)) 55 | } 56 | if(shiftValue.height !== 0) { 57 | scrollRef.current?.shift(shiftValue); 58 | onUpdateData?.({heights: heightsRef.current, ...shiftValue}); 59 | } 60 | setFinalData(data); 61 | }, [data, finalData, getHeight, keyExtractor, onUpdateData, scrollRef]); 62 | 63 | useEffect(() => { 64 | if(data === finalData) { 65 | return; 66 | } 67 | if(getItemLayout) { 68 | const newD = data.filter((d) => !heightsRef.current[keyExtractor(d)]); 69 | const oldHeights = heightsRef.current; 70 | heightsRef.current = data.reduce((p,c,i) => { 71 | p[keyExtractor(c)] = getItemLayout(data as any[], i).length; 72 | return p; 73 | }, {}); 74 | shift(newD, oldHeights); 75 | return; 76 | } 77 | setNewData(data.filter((d) => !heightsRef.current[keyExtractor(d)])); 78 | }, [data, finalData, getHeight, getItemLayout, keyExtractor, onUpdateData, scrollRef, shift]); 79 | 80 | useEffect(() => { 81 | if(getItemLayout || !newData.length) { 82 | return; 83 | } 84 | }, [newData, getItemLayout]); 85 | 86 | const onLayout = useCallback(({id, height}) => { 87 | heightsRef.current[id] = height; 88 | // check if there are missing elements 89 | const missing = data.some((d) => heightsRef.current[keyExtractor(d)] === undefined); 90 | if(missing) { 91 | return; 92 | } 93 | const oldHeights = heightsRef.current; 94 | // clean current heights (=> remove old heights) 95 | heightsRef.current = data.reduce((p,c) => { 96 | const id = keyExtractor(c); 97 | p[id] = oldHeights[id]; 98 | return p; 99 | }, {}); 100 | shift(newData, oldHeights); 101 | setNewData([]); 102 | }, [data, keyExtractor, newData, shift]); 103 | 104 | return { 105 | finalData, 106 | prerender: newData.length ? 107 | {newData.map((d) => {renderItem({item: d, prerendering: true})})} 108 | : undefined, 109 | getItemLayoutCustom: useCallback((data, index) => { 110 | const d = data[index]; 111 | const id = keyExtractor(d); 112 | return { 113 | index, 114 | length: heightsRef.current[id], 115 | offset: getHeight(data.slice(0, index)), 116 | } 117 | }, [getHeight, keyExtractor]), 118 | }; 119 | }; 120 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/example/reactnativebidirectionalflatlist/newarchitecture/MainApplicationReactNativeHost.java: -------------------------------------------------------------------------------- 1 | package com.example.reactnativebidirectionalflatlist.newarchitecture; 2 | 3 | import android.app.Application; 4 | import androidx.annotation.NonNull; 5 | import com.facebook.react.PackageList; 6 | import com.facebook.react.ReactInstanceManager; 7 | import com.facebook.react.ReactNativeHost; 8 | import com.facebook.react.ReactPackage; 9 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate; 10 | import com.facebook.react.bridge.JSIModulePackage; 11 | import com.facebook.react.bridge.JSIModuleProvider; 12 | import com.facebook.react.bridge.JSIModuleSpec; 13 | import com.facebook.react.bridge.JSIModuleType; 14 | import com.facebook.react.bridge.JavaScriptContextHolder; 15 | import com.facebook.react.bridge.ReactApplicationContext; 16 | import com.facebook.react.bridge.UIManager; 17 | import com.facebook.react.fabric.ComponentFactory; 18 | import com.facebook.react.fabric.CoreComponentsRegistry; 19 | import com.facebook.react.fabric.EmptyReactNativeConfig; 20 | import com.facebook.react.fabric.FabricJSIModuleProvider; 21 | import com.facebook.react.uimanager.ViewManagerRegistry; 22 | import com.example.reactnativebidirectionalflatlist.BuildConfig; 23 | import com.example.reactnativebidirectionalflatlist.newarchitecture.components.MainComponentsRegistry; 24 | import com.example.reactnativebidirectionalflatlist.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate; 25 | import java.util.ArrayList; 26 | import java.util.List; 27 | 28 | /** 29 | * A {@link ReactNativeHost} that helps you load everything needed for the New Architecture, both 30 | * TurboModule delegates and the Fabric Renderer. 31 | * 32 | *

Please note that this class is used ONLY if you opt-in for the New Architecture (see the 33 | * `newArchEnabled` property). Is ignored otherwise. 34 | */ 35 | public class MainApplicationReactNativeHost extends ReactNativeHost { 36 | public MainApplicationReactNativeHost(Application application) { 37 | super(application); 38 | } 39 | 40 | @Override 41 | public boolean getUseDeveloperSupport() { 42 | return BuildConfig.DEBUG; 43 | } 44 | 45 | @Override 46 | protected List getPackages() { 47 | List packages = new PackageList(this).getPackages(); 48 | // Packages that cannot be autolinked yet can be added manually here, for example: 49 | // packages.add(new MyReactNativePackage()); 50 | // TurboModules must also be loaded here providing a valid TurboReactPackage implementation: 51 | // packages.add(new TurboReactPackage() { ... }); 52 | // If you have custom Fabric Components, their ViewManagers should also be loaded here 53 | // inside a ReactPackage. 54 | return packages; 55 | } 56 | 57 | @Override 58 | protected String getJSMainModuleName() { 59 | return "index"; 60 | } 61 | 62 | @NonNull 63 | @Override 64 | protected ReactPackageTurboModuleManagerDelegate.Builder 65 | getReactPackageTurboModuleManagerDelegateBuilder() { 66 | // Here we provide the ReactPackageTurboModuleManagerDelegate Builder. This is necessary 67 | // for the new architecture and to use TurboModules correctly. 68 | return new MainApplicationTurboModuleManagerDelegate.Builder(); 69 | } 70 | 71 | @Override 72 | protected JSIModulePackage getJSIModulePackage() { 73 | return new JSIModulePackage() { 74 | @Override 75 | public List getJSIModules( 76 | final ReactApplicationContext reactApplicationContext, 77 | final JavaScriptContextHolder jsContext) { 78 | final List specs = new ArrayList<>(); 79 | 80 | // Here we provide a new JSIModuleSpec that will be responsible of providing the 81 | // custom Fabric Components. 82 | specs.add( 83 | new JSIModuleSpec() { 84 | @Override 85 | public JSIModuleType getJSIModuleType() { 86 | return JSIModuleType.UIManager; 87 | } 88 | 89 | @Override 90 | public JSIModuleProvider getJSIModuleProvider() { 91 | final ComponentFactory componentFactory = new ComponentFactory(); 92 | CoreComponentsRegistry.register(componentFactory); 93 | 94 | // Here we register a Components Registry. 95 | // The one that is generated with the template contains no components 96 | // and just provides you the one from React Native core. 97 | MainComponentsRegistry.register(componentFactory); 98 | 99 | final ReactInstanceManager reactInstanceManager = getReactInstanceManager(); 100 | 101 | ViewManagerRegistry viewManagerRegistry = 102 | new ViewManagerRegistry( 103 | reactInstanceManager.getOrCreateViewManagers(reactApplicationContext)); 104 | 105 | return new FabricJSIModuleProvider( 106 | reactApplicationContext, 107 | componentFactory, 108 | new EmptyReactNativeConfig(), 109 | viewManagerRegistry); 110 | } 111 | }); 112 | return specs; 113 | } 114 | }; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /src/ScrollView.tsx: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 2 | // @ts-nocheck 3 | 4 | import React, { Component, forwardRef } from 'react'; 5 | import { PixelRatio, Platform, ScrollView as ScrollViewRN, ScrollViewProps, StyleSheet, View } from 'react-native'; 6 | import { BidirectionalFlatlist } from './BidirectionalFlatlist'; 7 | import type { ShiftFunction } from './types'; 8 | 9 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 10 | // @ts-ignore 11 | const ScrollViewRNRaw: Component = ScrollViewRN.render().type; // hack to get inner type of ScrollView 12 | 13 | export class ScrollViewComponent extends ScrollViewRNRaw { 14 | constructor(props: ScrollViewProps) { 15 | super(props); 16 | } 17 | 18 | shift: ShiftFunction = ({ offset, height }: { offset: number; height: number }) => { 19 | this.getNativeScrollRef().setNativeProps({ 20 | shiftOffset: PixelRatio.getPixelSizeForLayoutSize(offset), 21 | shiftHeight: PixelRatio.getPixelSizeForLayoutSize(height), 22 | }); 23 | } 24 | 25 | render() { 26 | const NativeDirectionalScrollView = BidirectionalFlatlist; 27 | const NativeDirectionalScrollContentView = View; 28 | 29 | const contentContainerStyle = [this.props.contentContainerStyle]; 30 | // if (__DEV__ && this.props.style !== undefined) { 31 | // const style = StyleSheet.flatten(this.props.style); 32 | // const childLayoutProps = ['alignItems', 'justifyContent'].filter( 33 | // (prop) => style && style[prop] !== undefined 34 | // ); 35 | // invariant( 36 | // childLayoutProps.length === 0, 37 | // 'ScrollView child layout (' + 38 | // JSON.stringify(childLayoutProps) + 39 | // ') must be applied through the contentContainerStyle prop.' 40 | // ); 41 | // } 42 | 43 | const contentSizeChangeProps = 44 | this.props.onContentSizeChange == null 45 | ? null 46 | : { 47 | onLayout: this._handleContentOnLayout, 48 | }; 49 | 50 | const { stickyHeaderIndices } = this.props; 51 | const children = this.props.children; 52 | 53 | const hasStickyHeaders = 54 | Array.isArray(stickyHeaderIndices) && stickyHeaderIndices.length > 0; 55 | 56 | const contentContainer = ( 57 | 70 | {children} 71 | 72 | ); 73 | 74 | const alwaysBounceHorizontal = 75 | this.props.alwaysBounceHorizontal !== undefined 76 | ? this.props.alwaysBounceHorizontal 77 | : this.props.horizontal; 78 | 79 | const alwaysBounceVertical = 80 | this.props.alwaysBounceVertical !== undefined 81 | ? this.props.alwaysBounceVertical 82 | : !this.props.horizontal; 83 | 84 | const baseStyle = styles.baseVertical; 85 | const props = { 86 | ...this.props, 87 | alwaysBounceHorizontal, 88 | alwaysBounceVertical, 89 | style: StyleSheet.compose(baseStyle, this.props.style), 90 | // Override the onContentSizeChange from props, since this event can 91 | // bubble up from TextInputs 92 | onContentSizeChange: null, 93 | onLayout: this._handleLayout, 94 | onMomentumScrollBegin: this._handleMomentumScrollBegin, 95 | onMomentumScrollEnd: this._handleMomentumScrollEnd, 96 | onResponderGrant: this._handleResponderGrant, 97 | onResponderReject: this._handleResponderReject, 98 | onResponderRelease: this._handleResponderRelease, 99 | onResponderTerminationRequest: this._handleResponderTerminationRequest, 100 | onScrollBeginDrag: this._handleScrollBeginDrag, 101 | onScrollEndDrag: this._handleScrollEndDrag, 102 | onScrollShouldSetResponder: this._handleScrollShouldSetResponder, 103 | onStartShouldSetResponder: this._handleStartShouldSetResponder, 104 | onStartShouldSetResponderCapture: 105 | this._handleStartShouldSetResponderCapture, 106 | onTouchEnd: this._handleTouchEnd, 107 | onTouchMove: this._handleTouchMove, 108 | onTouchStart: this._handleTouchStart, 109 | onTouchCancel: this._handleTouchCancel, 110 | onScroll: this._handleScroll, 111 | scrollEventThrottle: hasStickyHeaders 112 | ? 1 113 | : this.props.scrollEventThrottle, 114 | sendMomentumEvents: 115 | this.props.onMomentumScrollBegin || this.props.onMomentumScrollEnd 116 | ? true 117 | : false, 118 | // default to true 119 | snapToStart: this.props.snapToStart !== false, 120 | // default to true 121 | snapToEnd: this.props.snapToEnd !== false, 122 | // pagingEnabled is overridden by snapToInterval / snapToOffsets 123 | pagingEnabled: Platform.select({ 124 | // on iOS, pagingEnabled must be set to false to have snapToInterval / snapToOffsets work 125 | ios: 126 | this.props.pagingEnabled === true && 127 | this.props.snapToInterval == null && 128 | this.props.snapToOffsets == null, 129 | // on Android, pagingEnabled must be set to true to have snapToInterval / snapToOffsets work 130 | android: 131 | this.props.pagingEnabled === true || 132 | this.props.snapToInterval != null || 133 | this.props.snapToOffsets != null, 134 | }), 135 | }; 136 | 137 | // const { decelerationRate } = this.props; 138 | // if (decelerationRate != null) { 139 | // props.decelerationRate = processDecelerationRate(decelerationRate); 140 | // } 141 | 142 | const scrollViewRef = this._scrollView.getForwardingRef( 143 | this.props.scrollViewRef, 144 | ); 145 | 146 | return ( 147 | 148 | {contentContainer} 149 | 150 | ); 151 | } 152 | } 153 | 154 | const styles = StyleSheet.create({ 155 | baseVertical: { 156 | flexGrow: 1, 157 | flexShrink: 1, 158 | flexDirection: 'column', 159 | overflow: 'scroll', 160 | }, 161 | }); 162 | 163 | export type ScrollViewType = typeof ScrollViewRN & {shift: (options: {offset: number; height: number}) => void}; 164 | 165 | export const ScrollView: ScrollViewType = forwardRef((props, ref) => { 166 | return 167 | }); 168 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC, ReactNode, useCallback, useContext, useMemo, useState } from 'react'; 2 | 3 | import { Button, FlatList, Text, TouchableOpacity, View } from 'react-native'; 4 | import BidirectionalFlatList from 'react-native-bidirectional-flatlist'; 5 | import Reanimated, { useAnimatedRef } from 'react-native-reanimated'; 6 | 7 | const FlatListReanimated = Reanimated.createAnimatedComponent(BidirectionalFlatList); 8 | 9 | interface MessageType { 10 | id: string; 11 | color: string; 12 | height: number; 13 | } 14 | 15 | let counter = 1; 16 | const getIdNumber = () => counter++; 17 | let block = 1; 18 | const getBlockNumber = () => block++; 19 | 20 | const generateData = (howMany = 20, height: number | undefined = undefined): MessageType[] => { 21 | const colors = [ 22 | 'red', 23 | 'green', 24 | 'blue', 25 | 'yellow', 26 | 'purple', 27 | 'brown', 28 | 'magenta', 29 | 'cyan', 30 | ]; 31 | const color = colors[getBlockNumber() % colors.length] as string; 32 | return Array.from(new Array(howMany)).map(() => { 33 | const id = getIdNumber(); 34 | return { 35 | id: id.toString(), 36 | color, 37 | height: height ?? Math.floor(50 + Math.random() * 100), 38 | }; 39 | }); 40 | }; 41 | 42 | const Message: FC = ({ id, color, height }) => { 43 | if(!height) { 44 | return null; 45 | } 46 | return ( 47 | 56 | 63 | {id} 64 | 65 | 66 | ); 67 | }; 68 | 69 | 70 | const types = ['FlatList', 'AnimatedFlatList', 'getItemLayout'] as const; 71 | type Type = typeof types[number]; 72 | 73 | const ExampleLink = ({type}: {type: Type}) => { 74 | const {setType} = useContext(ExampleContext); 75 | const onPress = useCallback(() => { 76 | setType(type); 77 | }, [setType, type]); 78 | return {type}; 79 | } 80 | 81 | const ExampleContext = React.createContext<{type: string | undefined; back: () => unknown; setType: (type: Type) => unknown}>({type: undefined, back: () => {/* placeholder */}, setType: (_type) => {/* placeholder */}}); 82 | 83 | const Example = ({children}: {children: (props: any) => ReactNode}) => { 84 | const [puffer] = useState(() => generateData(20, 0)); 85 | const [data, setData] = useState([]); 86 | 87 | const ref = useAnimatedRef(); 88 | 89 | const renderItem = useCallback(({item}) => { 90 | return 91 | }, []) 92 | 93 | const keyExtractor = useCallback((item) => item.id, []); 94 | 95 | const removeFirst = useCallback(async () => { 96 | setData((x) => x.slice(1)); 97 | }, []); 98 | 99 | const prependAndRemoveFirst = useCallback(async () => { 100 | const newData = generateData(5); 101 | setData((x) => [...newData, ...x.slice(1)]); 102 | }, []); 103 | 104 | const prepend = useCallback(async () => { 105 | const newData = generateData(20); 106 | setData((x) => [...newData, ...x]); 107 | }, []); 108 | 109 | const append = useCallback(async () => { 110 | const newData = generateData(); 111 | setData((x) => [...x, ...newData]); 112 | }, []); 113 | 114 | const reset = useCallback(() => { 115 | setData([]); 116 | }, []); 117 | 118 | const finalData = useMemo(() => [...data, ...puffer], [data, puffer]); 119 | 120 | const props = { 121 | windowSize: 21, 122 | maxToRenderPerBatch: 20, 123 | initialNumToRender: 20, 124 | data: finalData, 125 | renderItem, 126 | keyExtractor, 127 | ref, 128 | } 129 | 130 | return 131 | {({type, back}) => <> 132 | {children(props)} 133 | 141 |