diff --git a/.eslintrc.js b/.eslintrc.js index dcf0be0..61dccec 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,16 +1,5 @@ module.exports = { root: true, - extends: '@react-native-community', - parser: '@typescript-eslint/parser', - plugins: ['@typescript-eslint'], - overrides: [ - { - files: ['*.ts', '*.tsx'], - rules: { - '@typescript-eslint/no-shadow': ['error'], - 'no-shadow': 'off', - 'no-undef': 'off', - }, - }, - ], + extends: '@react-native', + ignorePatterns: ['/coverage/*'], }; diff --git a/.npmignore b/.npmignore index 29748fc..2ebdc98 100644 --- a/.npmignore +++ b/.npmignore @@ -1,3 +1,3 @@ coverage/ example/ -demo/ \ No newline at end of file +demo/ diff --git a/README.md b/README.md index 439b335..34c904e 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,67 @@ # React Native Userpic -Full featured and highly customizable React Native component to display user avatars. The component allows you to show gravatar images, fallback to user's initials, fine tune shape and size, add badges and custom statuses to avatar image. + + +The ultimate React Native component for displaying user avatars written in TypeScript with a strong focus on performance. This fully featured and highly customizable component allows you to show Gravatar images by providing an email address, fallback to user's initials, fine-tune the shape and size of avatars, add badges and custom statuses to the avatar image. + +
--- - + -**Shape that fits your design** -Square, circle, rounded borders. For your convenience, the `borderRadius` prop supports percent values just like in CSS. +**Control the shape of the avatars** +The default circular shape can be changed by specifying a custom border radius. The `style` prop enables you to override the default styles, such as adding a border. --- - + -**Custom fallback image or even emoji** -For users without an image you can leave the default profile icon, or use your own fallback image, or even show an emoji. +**Custom fallback image or emoji** +For users without an image, you have the option to display the default avatar icon, provide a custom fallback image, or even show an emoji. --- - + **Fallback to user's initials** -Another option for those who have no image is to display their initials. The `colorize` option will generate unique colors based on user's name. +Another option for users without an image is to display their initials. By enabling the `colorize` option, unique color can be generated based on the user's name. --- - + **Gravatar support** -Add user's email address to display their gravatar image. This can be combined with your own avatar images as a fallback option. +Include the user's email address to display their Gravatar image. This can be combined with your own avatar image to provide a fallback option. --- - + **Numeric badges** -You can add a badge to display unread messages count, or user's online/offline status. Badge position can be customized as well. +You can add a badge to display the count of unread messages or the online/offline status of the user. The position of the badge can also be customized. --- - + **Custom badges** -Another way of using badges is allowing your users to attach a status icon to their avatar by picking up an emoji. +Another option for utilizing avatar badges is to display a custom status icon, such as an emoji, for example. --- ## Installation +### yarn ```sh yarn add react-native-userpic -# or +``` +### npm +```sh npm install react-native-userpic ``` -## Usage +## Basic Example ```jsx import React from 'react'; @@ -78,7 +85,7 @@ const styles = StyleSheet.create({ export default MyComponent; ``` -## Advanced example +## Advanced Example ```jsx import React from 'react'; @@ -87,21 +94,22 @@ import { Userpic } from 'react-native-userpic'; const defaultImage = require('./assets/defaultAvatar.png'); const badgeProps = { - size: 30, - borderRadius: 5, + size: 24, + radius: 5, + position: 'top-left', } -const MyComponent = ({ userImage, userEmail, userName }) => ( +const MyComponent = ({ userImage, userEmail, userName, unreadCount }) => ( @@ -123,35 +131,51 @@ export default MyComponent; Prop | Type | Default | Description ---|---|---|--- -`size` | number | 50 | Size of the image -`borderRadius` | number \| string | '50%' | In addition to a number you can use percentage strings "0%...50%" where "50%" creates circle shape -`name` | string | | User name for showing initials when no image provided -`email` | string | | User email for showing their gravatar image -`colorize` | boolean | false | This will generate a unique color when showing initials -`source` | ImageSourcePropType | | The image source (either a remote URL or a local file resource) +`size` | number | `50` | Width and height of the avatar +`name` | string | | User name for showing initials +`email` | string | | User email for showing Gravatar image +`source` | ImageSourcePropType | | The avatar image source (either a remote URL or a local file resource) `defaultSource` | ImageSourcePropType | | The fallback image source -`style` | ViewStyle | | Style of the container -`textStyle` | TextStyle | | Style of the initials text -`imageStyle` | ImageStyle | | Style of the image -`badge` | number \| boolean \| string | | A number or string value to show in the badge, passing `true` will show a color dot -`badgeColor` | string | | Color of the badge -`badgePosition` | string | 'top-right' | Possible values are `top-right`, `bottom-right`, `bottom-left`, `top-left'` -`badgeProps` | BadgeProps | | See [badge props](#badge-props) below +`color` | string | `#aeaeb2` | Background color of the avatar +`radius` | number | `size / 2` | Border radius of the avatar +`colorize` | boolean | `false` | To generate a unique background color when displaying initials +`style` | ViewStyle | | Style object applied to the image or initials container +`textStyle` | TextStyle | | Style object applied to the initials text +`badge` | number \| string \| boolean | | A number or string value to show in the badge, or `true` to display a color dot +`badgeColor` | string | | Background color of the badge +`badgeProps` | BadgeProps | | [Badge props](#badge-props) excluding `value`, `color`, and `parentRadius` + +## Badge Component -## Badge + -You can also use the badge as a stand-alone component. +The badge can be used as a standalone component. The font size of the badge text value is calculated based on the `size` prop, so you normally don't have to specify it. By default, the badge appears with a spring animation, which can be disabled using the `animate` prop. To position the badge absolutely over its parent, use the `position` prop along with the `parentRadius` prop. + +
```jsx -import React from 'react'; -import { View, StyleSheet } from 'react-native'; +import React, { useState } from 'react'; +import { StyleSheet, Text, TouchableHighlight, View } from 'react-native'; import { Badge } from 'react-native-userpic'; -const MyComponent = ({ count }) => ( - - - -); +const MyComponent = () => { + const [badge, setBadge] = useState(0); + + return ( + + setBadge(badge + 1)} + > + <> + Press me + + + + + ); +}; const styles = StyleSheet.create({ wrapper: { @@ -159,24 +183,45 @@ const styles = StyleSheet.create({ alignItems: 'center', justifyContent: 'center', }, + button: { + width: 200, + height: 44, + marginTop: 20, + borderRadius: 22, + alignSelf: 'center', + alignItems: 'center', + justifyContent: 'center', + backgroundColor: '#2FAFC7', + }, + buttonText: { + color: '#fff', + fontSize: 17, + fontWeight: '600', + }, }); export default MyComponent; ``` -## Badge props +## Badge Props Prop | Type | Default | Description ---|---|---|--- -`size` | number | 20 | Size (height) of the badge -`color` | string | '#ff3b30' | Background color of the badge -`borderRadius` | number \| string | '50%' | In addition to a number you can use percentage strings "0%...50%" where "50%" creates a circle or pill shape -`animate` | boolean | true | When `true`, the badge will appear with a spring animation -`value` | number \| boolean \| string | | A number or string value to show in the badge, passing `true` will show a color dot -`limit` | number \| boolean | 99 | Will show "99+" when the value exceeds the limit, set `false` to turn it off -`style` | ViewStyle | | Style of the container -`textStyle` | TextStyle | | Style of the text value +`size` | number | `20` | Height and min width of the badge +`color` | string | `#ff3b30` | Background color of the badge +`radius` | number | `size / 2` | Border radius of the badge +`animate` | boolean | `true` | To animate appearance with a spring animation +`value` | number \| boolean \| string | | A number or string value to show in the badge, or `true` to display a color dot +`limit` | number | `99` | To display "99+" when the `value` exceeds the limit, set `0` to disable +`parentRadius` | number | `0` | Border radius of the parent container, used to position the badge more precisely +`position` | BadgePositions | | To position the badge absolutely over its parent, the allowed options are `top-left`, `top-right`, `bottom-left`, and `bottom-right` +`style` | ViewStyle | | Style object applied to the container +`textStyle` | TextStyle | | Style object applied to the text + +## Feedback + +I appreciate your feedback, so please star the repository if you like it. This is the best motivation for me to maintain the package and add new features. If you have any feature requests, found a bug, or have ideas for improvement, feel free to [open an issue](https://github.com/kolking/react-native-userpic/issues). ## License -MIT \ No newline at end of file +Licensed under the MIT license. diff --git a/demo/badge-button.gif b/demo/badge-button.gif new file mode 100644 index 0000000..3614b33 Binary files /dev/null and b/demo/badge-button.gif differ diff --git a/demo/hero.gif b/demo/hero.gif new file mode 100644 index 0000000..7bd61c5 Binary files /dev/null and b/demo/hero.gif differ diff --git a/example/.buckconfig b/example/.buckconfig deleted file mode 100644 index 934256c..0000000 --- a/example/.buckconfig +++ /dev/null @@ -1,6 +0,0 @@ - -[android] - target = Google Inc.:Google APIs:23 - -[maven_repositories] - central = https://repo1.maven.org/maven2 diff --git a/example/.gitignore b/example/.gitignore index 81570d9..0cab2ac 100644 --- a/example/.gitignore +++ b/example/.gitignore @@ -20,6 +20,7 @@ DerivedData *.hmap *.ipa *.xcuserstate +ios/.xcode.env.local # Android/IntelliJ # @@ -29,6 +30,9 @@ build/ local.properties *.iml *.hprof +.cxx/ +*.keystore +!debug.keystore # node.js # @@ -36,12 +40,6 @@ node_modules/ npm-debug.log yarn-error.log -# BUCK -buck-out/ -\.buckd/ -*.keystore -!debug.keystore - # fastlane # # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the @@ -49,9 +47,10 @@ buck-out/ # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/ -*/fastlane/report.xml -*/fastlane/Preview.html -*/fastlane/screenshots +**/fastlane/report.xml +**/fastlane/Preview.html +**/fastlane/screenshots +**/fastlane/test_output # Bundle artifact *.jsbundle @@ -59,3 +58,9 @@ buck-out/ # Ruby / CocoaPods /ios/Pods/ /vendor/bundle/ + +# Temporary files created by Metro to check the health of the file watcher +.metro-health-check* + +# testing +/coverage diff --git a/example/.ruby-version b/example/.ruby-version deleted file mode 100644 index a4dd9db..0000000 --- a/example/.ruby-version +++ /dev/null @@ -1 +0,0 @@ -2.7.4 diff --git a/example/.watchmanconfig b/example/.watchmanconfig index 9e26dfe..0967ef4 100644 --- a/example/.watchmanconfig +++ b/example/.watchmanconfig @@ -1 +1 @@ -{} \ No newline at end of file +{} diff --git a/example/App.tsx b/example/App.tsx index 69a1602..4fa7e39 100644 --- a/example/App.tsx +++ b/example/App.tsx @@ -1,6 +1,14 @@ -import React from 'react'; -import { Appearance, SafeAreaView, StatusBar, StyleSheet, Text, View } from 'react-native'; -import { Userpic } from 'react-native-userpic'; +import React, { useCallback, useState } from 'react'; +import { + Appearance, + ImageSourcePropType, + StatusBar, + StyleSheet, + Text, + TouchableHighlight, + View, +} from 'react-native'; +import { Badge, Userpic, UserpicProps } from 'react-native-userpic'; StatusBar.setBarStyle('light-content'); @@ -8,80 +16,118 @@ function colorScheme(lightColor: string, darkColor: string) { return Appearance.getColorScheme() === 'dark' ? darkColor : lightColor; } -// Random user images: -const images = [ - 'https://minimaltoolkit.com/images/randomdata/male/78.jpg', - 'https://minimaltoolkit.com/images/randomdata/male/62.jpg', - 'https://minimaltoolkit.com/images/randomdata/male/46.jpg', - 'https://minimaltoolkit.com/images/randomdata/female/107.jpg', - 'https://minimaltoolkit.com/images/randomdata/female/70.jpg', - 'https://minimaltoolkit.com/images/randomdata/female/96.jpg', +const IMAGES = [ + { uri: 'https://example.com/image.png' }, + { uri: 'https://xsgames.co/randomusers/assets/avatars/female/44.jpg' }, + { uri: 'https://xsgames.co/randomusers/assets/avatars/male/42.jpg' }, + { uri: 'https://xsgames.co/randomusers/assets/avatars/female/38.jpg' }, + { uri: 'https://xsgames.co/randomusers/assets/avatars/male/73.jpg' }, + { uri: 'https://xsgames.co/randomusers/assets/avatars/female/2.jpg' }, + { uri: 'https://xsgames.co/randomusers/assets/avatars/male/46.jpg' }, ]; -const App = () => ( - - +const App = () => { + const [badge, setBadge] = useState(0); + const [image, setImage] = useState(1); + const [badImage, setBadImage] = useState(); + + const toggleBadge = useCallback(() => { + console.log('-- STATE UPDATED --'); + setBadge(badge === 5 ? 0 : badge + 1); + }, [badge]); + + const toggleImage = useCallback(() => { + console.log('-- STATE UPDATED --'); + setImage(image + 1 === IMAGES.length ? 0 : image + 1); + }, [image]); + + const toggleBadImage = useCallback(() => { + console.log('-- STATE UPDATED --'); + setBadImage(badImage ? undefined : IMAGES[0]); + }, [badImage]); + + return ( + Shape - - - + + + - No image - + + No image + + Initials - + - + - Image - - - + + Image + + + + Gravatar - - - + + + - Badge - - - + + Badge + + + + Status - - - + + + Size - - - + + + + + <> + Press me + + + - -); + ); +}; const styles = StyleSheet.create({ container: { flex: 1, + padding: 30, justifyContent: 'center', backgroundColor: colorScheme('#fff', '#212124'), }, - content: { - margin: 30, - }, row: { marginVertical: 10, flexDirection: 'row', @@ -102,10 +148,26 @@ const styles = StyleSheet.create({ badgeTextStyle: { marginHorizontal: 0, }, + button: { + width: 150, + height: 44, + marginTop: 20, + borderRadius: 22, + alignSelf: 'center', + alignItems: 'center', + justifyContent: 'center', + backgroundColor: '#2FAFC7', + }, + buttonText: { + color: '#fff', + fontSize: 17, + fontWeight: '600', + }, }); -const statusBadgeProps = { +const statusBadgeProps: UserpicProps['badgeProps'] = { size: 22, + position: 'bottom-right', style: styles.badgeStyle, textStyle: styles.badgeTextStyle, }; diff --git a/example/App2.tsx b/example/App2.tsx new file mode 100644 index 0000000..83c22a9 --- /dev/null +++ b/example/App2.tsx @@ -0,0 +1,112 @@ +import React, { useCallback, useState } from 'react'; +import { Pressable, StyleSheet, View } from 'react-native'; +import { Userpic, UserpicProps } from 'react-native-userpic'; + +const badgeProps: UserpicProps[] = [ + { + defaultSource: require('./assets/custom.png'), + }, + { + name: '👩🏼', + }, + { + name: 'React Native', + colorize: true, + }, + { + badge: 0, + badgeProps: { size: 30 }, + source: { uri: 'https://xsgames.co/randomusers/assets/avatars/female/44.jpg' }, + }, + { + badge: 3, + badgeProps: { size: 30 }, + source: { uri: 'https://xsgames.co/randomusers/assets/avatars/female/44.jpg' }, + }, + { + badge: 4, + badgeProps: { size: 30 }, + source: { uri: 'https://xsgames.co/randomusers/assets/avatars/female/44.jpg' }, + radius: 40, + }, + { + badge: 5, + badgeProps: { size: 30 }, + source: { uri: 'https://xsgames.co/randomusers/assets/avatars/female/44.jpg' }, + radius: 30, + }, + { + badge: false, + badgeProps: { size: 30 }, + source: { uri: 'https://xsgames.co/randomusers/assets/avatars/male/73.jpg' }, + }, + { + badge: true, + badgeColor: '#34c759', + badgeProps: { size: 30 }, + source: { uri: 'https://xsgames.co/randomusers/assets/avatars/male/73.jpg' }, + }, + { + badge: '', + badgeProps: { size: 30 }, + source: { uri: 'https://xsgames.co/randomusers/assets/avatars/female/38.jpg' }, + }, + { + badge: '👋', + badgeProps: { + size: 30, + position: 'bottom-right', + style: { + elevation: 0, + shadowOpacity: 0, + backgroundColor: '#212124', + }, + textStyle: { + marginHorizontal: 0, + }, + }, + source: { uri: 'https://xsgames.co/randomusers/assets/avatars/female/38.jpg' }, + }, +]; + +const App = () => { + const [props, setProps] = useState(0); + + const toggleProps = useCallback(() => { + setProps(props + 1 === badgeProps.length ? 0 : props + 1); + }, [props]); + + return ( + + + + + + ); +}; + +const styles = StyleSheet.create({ + wrapper: { + flex: 1, + alignItems: 'center', + justifyContent: 'center', + backgroundColor: '#212124', + }, + button: { + width: 200, + height: 44, + marginTop: 20, + borderRadius: 22, + alignSelf: 'center', + alignItems: 'center', + justifyContent: 'center', + backgroundColor: '#2FAFC7', + }, + buttonText: { + color: '#fff', + fontSize: 17, + fontWeight: '600', + }, +}); + +export default App; diff --git a/example/Gemfile b/example/Gemfile index 2c3edcf..1fa2c2e 100644 --- a/example/Gemfile +++ b/example/Gemfile @@ -1,6 +1,6 @@ source 'https://rubygems.org' # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version -ruby '2.7.4' +ruby ">= 2.6.10" -gem 'cocoapods', '~> 1.11', '>= 1.11.2' +gem 'cocoapods', '~> 1.12' diff --git a/example/Gemfile.lock b/example/Gemfile.lock new file mode 100644 index 0000000..aeab6a8 --- /dev/null +++ b/example/Gemfile.lock @@ -0,0 +1,100 @@ +GEM + remote: https://rubygems.org/ + specs: + CFPropertyList (3.0.6) + rexml + activesupport (6.1.7.3) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + zeitwerk (~> 2.3) + addressable (2.8.4) + public_suffix (>= 2.0.2, < 6.0) + algoliasearch (1.27.5) + httpclient (~> 2.8, >= 2.8.3) + json (>= 1.5.1) + atomos (0.1.3) + claide (1.1.0) + cocoapods (1.12.1) + addressable (~> 2.8) + claide (>= 1.0.2, < 2.0) + cocoapods-core (= 1.12.1) + cocoapods-deintegrate (>= 1.0.3, < 2.0) + cocoapods-downloader (>= 1.6.0, < 2.0) + cocoapods-plugins (>= 1.0.0, < 2.0) + cocoapods-search (>= 1.0.0, < 2.0) + cocoapods-trunk (>= 1.6.0, < 2.0) + cocoapods-try (>= 1.1.0, < 2.0) + colored2 (~> 3.1) + escape (~> 0.0.4) + fourflusher (>= 2.3.0, < 3.0) + gh_inspector (~> 1.0) + molinillo (~> 0.8.0) + nap (~> 1.0) + ruby-macho (>= 2.3.0, < 3.0) + xcodeproj (>= 1.21.0, < 2.0) + cocoapods-core (1.12.1) + activesupport (>= 5.0, < 8) + addressable (~> 2.8) + algoliasearch (~> 1.0) + concurrent-ruby (~> 1.1) + fuzzy_match (~> 2.0.4) + nap (~> 1.0) + netrc (~> 0.11) + public_suffix (~> 4.0) + typhoeus (~> 1.0) + cocoapods-deintegrate (1.0.5) + cocoapods-downloader (1.6.3) + cocoapods-plugins (1.0.0) + nap + cocoapods-search (1.0.1) + cocoapods-trunk (1.6.0) + nap (>= 0.8, < 2.0) + netrc (~> 0.11) + cocoapods-try (1.2.0) + colored2 (3.1.2) + concurrent-ruby (1.2.2) + escape (0.0.4) + ethon (0.16.0) + ffi (>= 1.15.0) + ffi (1.15.5) + fourflusher (2.3.1) + fuzzy_match (2.0.4) + gh_inspector (1.1.3) + httpclient (2.8.3) + i18n (1.14.1) + concurrent-ruby (~> 1.0) + json (2.6.3) + minitest (5.18.1) + molinillo (0.8.0) + nanaimo (0.3.0) + nap (1.1.0) + netrc (0.11.0) + public_suffix (4.0.7) + rexml (3.2.5) + ruby-macho (2.5.1) + typhoeus (1.4.0) + ethon (>= 0.9.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + xcodeproj (1.22.0) + CFPropertyList (>= 2.3.3, < 4.0) + atomos (~> 0.1.3) + claide (>= 1.0.2, < 2.0) + colored2 (~> 3.1) + nanaimo (~> 0.3.0) + rexml (~> 3.2.4) + zeitwerk (2.6.8) + +PLATFORMS + ruby + +DEPENDENCIES + cocoapods (~> 1.12) + +RUBY VERSION + ruby 2.6.10p210 + +BUNDLED WITH + 1.17.2 diff --git a/example/android/app/_BUCK b/example/android/app/_BUCK deleted file mode 100644 index a4cb8a5..0000000 --- a/example/android/app/_BUCK +++ /dev/null @@ -1,55 +0,0 @@ -# To learn about Buck see [Docs](https://buckbuild.com/). -# To run your application with Buck: -# - install Buck -# - `npm start` - to start the packager -# - `cd android` -# - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` -# - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck -# - `buck install -r android/app` - compile, install and run application -# - -load(":build_defs.bzl", "create_aar_targets", "create_jar_targets") - -lib_deps = [] - -create_aar_targets(glob(["libs/*.aar"])) - -create_jar_targets(glob(["libs/*.jar"])) - -android_library( - name = "all-libs", - exported_deps = lib_deps, -) - -android_library( - name = "app-code", - srcs = glob([ - "src/main/java/**/*.java", - ]), - deps = [ - ":all-libs", - ":build_config", - ":res", - ], -) - -android_build_config( - name = "build_config", - package = "com.example", -) - -android_resource( - name = "res", - package = "com.example", - res = "src/main/res", -) - -android_binary( - name = "app", - keystore = "//android/keystores:debug", - manifest = "src/main/AndroidManifest.xml", - package_type = "debug", - deps = [ - ":app-code", - ], -) diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle index 2156b2b..a3d064c 100644 --- a/example/android/app/build.gradle +++ b/example/android/app/build.gradle @@ -1,226 +1,85 @@ apply plugin: "com.android.application" - -import com.android.build.OutputFile -import org.apache.tools.ant.taskdefs.condition.Os +apply plugin: "com.facebook.react" /** - * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets - * and bundleReleaseJsAndAssets). - * These basically call `react-native bundle` with the correct arguments during the Android build - * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the - * bundle directly from the development server. Below you can see all the possible configurations - * and their defaults. If you decide to add a configuration block, make sure to add it before the - * `apply from: "../../node_modules/react-native/react.gradle"` line. - * - * project.ext.react = [ - * // the name of the generated asset file containing your JS bundle - * bundleAssetName: "index.android.bundle", - * - * // the entry file for bundle generation. If none specified and - * // "index.android.js" exists, it will be used. Otherwise "index.js" is - * // default. Can be overridden with ENTRY_FILE environment variable. - * entryFile: "index.android.js", - * - * // https://reactnative.dev/docs/performance#enable-the-ram-format - * bundleCommand: "ram-bundle", - * - * // whether to bundle JS and assets in debug mode - * bundleInDebug: false, - * - * // whether to bundle JS and assets in release mode - * bundleInRelease: true, - * - * // whether to bundle JS and assets in another build variant (if configured). - * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants - * // The configuration property can be in the following formats - * // 'bundleIn${productFlavor}${buildType}' - * // 'bundleIn${buildType}' - * // bundleInFreeDebug: true, - * // bundleInPaidRelease: true, - * // bundleInBeta: true, - * - * // whether to disable dev mode in custom build variants (by default only disabled in release) - * // for example: to disable dev mode in the staging build type (if configured) - * devDisabledInStaging: true, - * // The configuration property can be in the following formats - * // 'devDisabledIn${productFlavor}${buildType}' - * // 'devDisabledIn${buildType}' - * - * // the root of your project, i.e. where "package.json" lives - * root: "../../", - * - * // where to put the JS bundle asset in debug mode - * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", - * - * // where to put the JS bundle asset in release mode - * jsBundleDirRelease: "$buildDir/intermediates/assets/release", - * - * // where to put drawable resources / React Native assets, e.g. the ones you use via - * // require('./image.png')), in debug mode - * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", - * - * // where to put drawable resources / React Native assets, e.g. the ones you use via - * // require('./image.png')), in release mode - * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", - * - * // by default the gradle tasks are skipped if none of the JS files or assets change; this means - * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to - * // date; if you have any other folders that you want to ignore for performance reasons (gradle - * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ - * // for example, you might want to remove it from here. - * inputExcludes: ["android/**", "ios/**"], - * - * // override which node gets called and with what additional arguments - * nodeExecutableAndArgs: ["node"], - * - * // supply additional arguments to the packager - * extraPackagerArgs: [] - * ] + * This is the configuration block to customize your React Native Android app. + * By default you don't need to apply any configuration, just uncomment the lines you need. */ - -project.ext.react = [ - enableHermes: false, // clean and rebuild if changing -] - -apply from: "../../node_modules/react-native/react.gradle" - -/** - * Set this to true to create two separate APKs instead of one: - * - An APK that only works on ARM devices - * - An APK that only works on x86 devices - * The advantage is the size of the APK is reduced by about 4MB. - * Upload all the APKs to the Play Store and people will download - * the correct one based on the CPU architecture of their device. - */ -def enableSeparateBuildPerCPUArchitecture = false +react { + /* Folders */ + // The root of your project, i.e. where "package.json" lives. Default is '..' + // root = file("../") + // The folder where the react-native NPM package is. Default is ../node_modules/react-native + // reactNativeDir = file("../node_modules/react-native") + // The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen + // codegenDir = file("../node_modules/@react-native/codegen") + // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js + // cliFile = file("../node_modules/react-native/cli.js") + + /* Variants */ + // The list of variants to that are debuggable. For those we're going to + // skip the bundling of the JS bundle and the assets. By default is just 'debug'. + // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. + // debuggableVariants = ["liteDebug", "prodDebug"] + + /* Bundling */ + // A list containing the node command and its flags. Default is just 'node'. + // nodeExecutableAndArgs = ["node"] + // + // The command to run when bundling. By default is 'bundle' + // bundleCommand = "ram-bundle" + // + // The path to the CLI configuration file. Default is empty. + // bundleConfig = file(../rn-cli.config.js) + // + // The name of the generated asset file containing your JS bundle + // bundleAssetName = "MyApplication.android.bundle" + // + // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' + // entryFile = file("../js/MyApplication.android.js") + // + // A list of extra flags to pass to the 'bundle' commands. + // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle + // extraPackagerArgs = [] + + /* Hermes Commands */ + // The hermes compiler command to run. By default it is 'hermesc' + // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" + // + // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" + // hermesFlags = ["-O", "-output-source-map"] +} /** - * Run Proguard to shrink the Java bytecode in release builds. + * Set this to true to Run Proguard on Release builds to minify the Java bytecode. */ def enableProguardInReleaseBuilds = false /** - * The preferred build flavor of JavaScriptCore. + * The preferred build flavor of JavaScriptCore (JSC) * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that - * give correct results when using with locales other than en-US. Note that + * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'org.webkit:android-jsc:+' -/** - * Whether to enable the Hermes VM. - * - * This should be set on project.ext.react and that value will be read here. If it is not set - * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode - * and the benefits of using Hermes will therefore be sharply reduced. - */ -def enableHermes = project.ext.react.get("enableHermes", false); - -/** - * Architectures to build native code for. - */ -def reactNativeArchitectures() { - def value = project.getProperties().get("reactNativeArchitectures") - return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"] -} - android { ndkVersion rootProject.ext.ndkVersion compileSdkVersion rootProject.ext.compileSdkVersion + namespace "com.example" defaultConfig { applicationId "com.example" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" - buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString() - - if (isNewArchitectureEnabled()) { - // We configure the NDK build only if you decide to opt-in for the New Architecture. - externalNativeBuild { - ndkBuild { - arguments "APP_PLATFORM=android-21", - "APP_STL=c++_shared", - "NDK_TOOLCHAIN_VERSION=clang", - "GENERATED_SRC_DIR=$buildDir/generated/source", - "PROJECT_BUILD_DIR=$buildDir", - "REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid", - "REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build" - cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1" - cppFlags "-std=c++17" - // Make sure this target name is the same you specify inside the - // src/main/jni/Android.mk file for the `LOCAL_MODULE` variable. - targets "example_appmodules" - - // Fix for windows limit on number of character in file paths and in command lines - if (Os.isFamily(Os.FAMILY_WINDOWS)) { - arguments "NDK_APP_SHORT_COMMANDS=true" - } - } - } - if (!enableSeparateBuildPerCPUArchitecture) { - ndk { - abiFilters (*reactNativeArchitectures()) - } - } - } - } - - if (isNewArchitectureEnabled()) { - // We configure the NDK build only if you decide to opt-in for the New Architecture. - externalNativeBuild { - ndkBuild { - path "$projectDir/src/main/jni/Android.mk" - } - } - def reactAndroidProjectDir = project(':ReactAndroid').projectDir - def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) { - dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck") - from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib") - into("$buildDir/react-ndk/exported") - } - def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) { - dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck") - from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib") - into("$buildDir/react-ndk/exported") - } - afterEvaluate { - // If you wish to add a custom TurboModule or component locally, - // you should uncomment this line. - // preBuild.dependsOn("generateCodegenArtifactsFromSchema") - preDebugBuild.dependsOn(packageReactNdkDebugLibs) - preReleaseBuild.dependsOn(packageReactNdkReleaseLibs) - - // Due to a bug inside AGP, we have to explicitly set a dependency - // between configureNdkBuild* tasks and the preBuild tasks. - // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732 - configureNdkBuildRelease.dependsOn(preReleaseBuild) - configureNdkBuildDebug.dependsOn(preDebugBuild) - reactNativeArchitectures().each { architecture -> - tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure { - dependsOn("preDebugBuild") - } - tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure { - dependsOn("preReleaseBuild") - } - } - } - } - - splits { - abi { - reset() - enable enableSeparateBuildPerCPUArchitecture - universalApk false // If true, also generate a universal APK - include (*reactNativeArchitectures()) - } } signingConfigs { debug { @@ -242,79 +101,23 @@ android { proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } - - // applicationVariants are e.g. debug, release - applicationVariants.all { variant -> - variant.outputs.each { output -> - // For each separate APK per architecture, set a unique version code as described here: - // https://developer.android.com/studio/build/configure-apk-splits.html - // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc. - def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] - def abi = output.getFilter(OutputFile.ABI) - if (abi != null) { // null for the universal-debug, universal-release variants - output.versionCodeOverride = - defaultConfig.versionCode * 1000 + versionCodes.get(abi) - } - - } - } } dependencies { - implementation fileTree(dir: "libs", include: ["*.jar"]) - - //noinspection GradleDynamicVersion - implementation "com.facebook.react:react-native:+" // From node_modules - - implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" - - debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") { - exclude group:'com.facebook.fbjni' - } + // The version of react-native is set by the React Native Gradle Plugin + implementation("com.facebook.react:react-android") + debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { - exclude group:'com.facebook.flipper' exclude group:'com.squareup.okhttp3', module:'okhttp' } - debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") { - exclude group:'com.facebook.flipper' - } - - if (enableHermes) { - def hermesPath = "../../node_modules/hermes-engine/android/"; - debugImplementation files(hermesPath + "hermes-debug.aar") - releaseImplementation files(hermesPath + "hermes-release.aar") + debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") + if (hermesEnabled.toBoolean()) { + implementation("com.facebook.react:hermes-android") } else { implementation jscFlavor } } -if (isNewArchitectureEnabled()) { - // If new architecture is enabled, we let you build RN from source - // Otherwise we fallback to a prebuilt .aar bundled in the NPM package. - // This will be applied to all the imported transtitive dependency. - configurations.all { - resolutionStrategy.dependencySubstitution { - substitute(module("com.facebook.react:react-native")) - .using(project(":ReactAndroid")).because("On New Architecture we're building React Native from source") - } - } -} - -// Run this once to be able to run the application with BUCK -// puts all compile dependencies into folder libs for BUCK to use -task copyDownloadableDepsToLibs(type: Copy) { - from configurations.implementation - into 'libs' -} - apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) - -def isNewArchitectureEnabled() { - // To opt-in for the New Architecture, you can either: - // - Set `newArchEnabled` to true inside the `gradle.properties` file - // - Invoke gradle with `-newArchEnabled=true` - // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true` - return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true" -} diff --git a/example/android/app/build_defs.bzl b/example/android/app/build_defs.bzl deleted file mode 100644 index fff270f..0000000 --- a/example/android/app/build_defs.bzl +++ /dev/null @@ -1,19 +0,0 @@ -"""Helper definitions to glob .aar and .jar targets""" - -def create_aar_targets(aarfiles): - for aarfile in aarfiles: - name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")] - lib_deps.append(":" + name) - android_prebuilt_aar( - name = name, - aar = aarfile, - ) - -def create_jar_targets(jarfiles): - for jarfile in jarfiles: - name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")] - lib_deps.append(":" + name) - prebuilt_jar( - name = name, - binary_jar = jarfile, - ) diff --git a/example/android/app/src/debug/java/com/example/ReactNativeFlipper.java b/example/android/app/src/debug/java/com/example/ReactNativeFlipper.java index 9ffdd88..e75580e 100644 --- a/example/android/app/src/debug/java/com/example/ReactNativeFlipper.java +++ b/example/android/app/src/debug/java/com/example/ReactNativeFlipper.java @@ -17,7 +17,6 @@ import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; -import com.facebook.flipper.plugins.react.ReactFlipperPlugin; import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; import com.facebook.react.ReactInstanceEventListener; import com.facebook.react.ReactInstanceManager; @@ -25,13 +24,16 @@ import com.facebook.react.modules.network.NetworkingModule; import okhttp3.OkHttpClient; +/** + * Class responsible of loading Flipper inside your React Native application. This is the debug + * flavor of it. Here you can add your own plugins and customize the Flipper setup. + */ public class ReactNativeFlipper { public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { if (FlipperUtils.shouldEnableFlipper(context)) { final FlipperClient client = AndroidFlipperClient.getInstance(context); client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); - client.addPlugin(new ReactFlipperPlugin()); client.addPlugin(new DatabasesFlipperPlugin(context)); client.addPlugin(new SharedPreferencesFlipperPlugin(context)); client.addPlugin(CrashReporterPlugin.getInstance()); diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml index ef3c312..4122f36 100644 --- a/example/android/app/src/main/AndroidManifest.xml +++ b/example/android/app/src/main/AndroidManifest.xml @@ -1,5 +1,4 @@ - + diff --git a/example/android/app/src/main/java/com/example/MainActivity.java b/example/android/app/src/main/java/com/example/MainActivity.java index 6fed471..8803ec4 100644 --- a/example/android/app/src/main/java/com/example/MainActivity.java +++ b/example/android/app/src/main/java/com/example/MainActivity.java @@ -2,7 +2,8 @@ import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivityDelegate; -import com.facebook.react.ReactRootView; +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; +import com.facebook.react.defaults.DefaultReactActivityDelegate; public class MainActivity extends ReactActivity { @@ -16,25 +17,16 @@ protected String getMainComponentName() { } /** - * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and - * you can specify the rendered you wish to use (Fabric or the older renderer). + * Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link + * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React + * (aka React 18) with two boolean flags. */ @Override protected ReactActivityDelegate createReactActivityDelegate() { - return new MainActivityDelegate(this, getMainComponentName()); - } - - public static class MainActivityDelegate extends ReactActivityDelegate { - public MainActivityDelegate(ReactActivity activity, String mainComponentName) { - super(activity, mainComponentName); - } - - @Override - protected ReactRootView createRootView() { - ReactRootView reactRootView = new ReactRootView(getContext()); - // If you opted-in for the New Architecture, we enable the Fabric Renderer. - reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED); - return reactRootView; - } + return new DefaultReactActivityDelegate( + this, + getMainComponentName(), + // If you opted-in for the New Architecture, we enable the Fabric Renderer. + DefaultNewArchitectureEntryPoint.getFabricEnabled()); } } diff --git a/example/android/app/src/main/java/com/example/MainApplication.java b/example/android/app/src/main/java/com/example/MainApplication.java index 61f1d42..dd666be 100644 --- a/example/android/app/src/main/java/com/example/MainApplication.java +++ b/example/android/app/src/main/java/com/example/MainApplication.java @@ -1,22 +1,19 @@ package com.example; import android.app.Application; -import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; -import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; -import com.facebook.react.config.ReactFeatureFlags; +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; +import com.facebook.react.defaults.DefaultReactNativeHost; import com.facebook.soloader.SoLoader; -import com.example.newarchitecture.MainApplicationReactNativeHost; -import java.lang.reflect.InvocationTargetException; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = - new ReactNativeHost(this) { + new DefaultReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; @@ -35,57 +32,31 @@ protected List getPackages() { protected String getJSMainModuleName() { return "index"; } - }; - private final ReactNativeHost mNewArchitectureNativeHost = - new MainApplicationReactNativeHost(this); + @Override + protected boolean isNewArchEnabled() { + return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; + } + + @Override + protected Boolean isHermesEnabled() { + return BuildConfig.IS_HERMES_ENABLED; + } + }; @Override public ReactNativeHost getReactNativeHost() { - if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { - return mNewArchitectureNativeHost; - } else { - return mReactNativeHost; - } + return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); - // If you opted-in for the New Architecture, we enable the TurboModule system - ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; SoLoader.init(this, /* native exopackage */ false); - initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); - } - - /** - * Loads Flipper in React Native templates. Call this in the onCreate method with something like - * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); - * - * @param context - * @param reactInstanceManager - */ - private static void initializeFlipper( - Context context, ReactInstanceManager reactInstanceManager) { - if (BuildConfig.DEBUG) { - try { - /* - We use reflection here to pick up the class that initializes Flipper, - since Flipper library is not available in release mode - */ - Class aClass = Class.forName("com.example.ReactNativeFlipper"); - aClass - .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) - .invoke(null, context, reactInstanceManager); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } + if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { + // If you opted-in for the New Architecture, we load the native entry point for this app. + DefaultNewArchitectureEntryPoint.load(); } + ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } } diff --git a/example/android/app/src/main/java/com/example/newarchitecture/MainApplicationReactNativeHost.java b/example/android/app/src/main/java/com/example/newarchitecture/MainApplicationReactNativeHost.java deleted file mode 100644 index c47bf27..0000000 --- a/example/android/app/src/main/java/com/example/newarchitecture/MainApplicationReactNativeHost.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.example.newarchitecture; - -import android.app.Application; -import androidx.annotation.NonNull; -import com.facebook.react.PackageList; -import com.facebook.react.ReactInstanceManager; -import com.facebook.react.ReactNativeHost; -import com.facebook.react.ReactPackage; -import com.facebook.react.ReactPackageTurboModuleManagerDelegate; -import com.facebook.react.bridge.JSIModulePackage; -import com.facebook.react.bridge.JSIModuleProvider; -import com.facebook.react.bridge.JSIModuleSpec; -import com.facebook.react.bridge.JSIModuleType; -import com.facebook.react.bridge.JavaScriptContextHolder; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.UIManager; -import com.facebook.react.fabric.ComponentFactory; -import com.facebook.react.fabric.CoreComponentsRegistry; -import com.facebook.react.fabric.EmptyReactNativeConfig; -import com.facebook.react.fabric.FabricJSIModuleProvider; -import com.facebook.react.uimanager.ViewManagerRegistry; -import com.example.BuildConfig; -import com.example.newarchitecture.components.MainComponentsRegistry; -import com.example.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate; -import java.util.ArrayList; -import java.util.List; - -/** - * A {@link ReactNativeHost} that helps you load everything needed for the New Architecture, both - * TurboModule delegates and the Fabric Renderer. - * - *

Please note that this class is used ONLY if you opt-in for the New Architecture (see the - * `newArchEnabled` property). Is ignored otherwise. - */ -public class MainApplicationReactNativeHost extends ReactNativeHost { - public MainApplicationReactNativeHost(Application application) { - super(application); - } - - @Override - public boolean getUseDeveloperSupport() { - return BuildConfig.DEBUG; - } - - @Override - protected List getPackages() { - List packages = new PackageList(this).getPackages(); - // Packages that cannot be autolinked yet can be added manually here, for example: - // packages.add(new MyReactNativePackage()); - // TurboModules must also be loaded here providing a valid TurboReactPackage implementation: - // packages.add(new TurboReactPackage() { ... }); - // If you have custom Fabric Components, their ViewManagers should also be loaded here - // inside a ReactPackage. - return packages; - } - - @Override - protected String getJSMainModuleName() { - return "index"; - } - - @NonNull - @Override - protected ReactPackageTurboModuleManagerDelegate.Builder - getReactPackageTurboModuleManagerDelegateBuilder() { - // Here we provide the ReactPackageTurboModuleManagerDelegate Builder. This is necessary - // for the new architecture and to use TurboModules correctly. - return new MainApplicationTurboModuleManagerDelegate.Builder(); - } - - @Override - protected JSIModulePackage getJSIModulePackage() { - return new JSIModulePackage() { - @Override - public List getJSIModules( - final ReactApplicationContext reactApplicationContext, - final JavaScriptContextHolder jsContext) { - final List specs = new ArrayList<>(); - - // Here we provide a new JSIModuleSpec that will be responsible of providing the - // custom Fabric Components. - specs.add( - new JSIModuleSpec() { - @Override - public JSIModuleType getJSIModuleType() { - return JSIModuleType.UIManager; - } - - @Override - public JSIModuleProvider getJSIModuleProvider() { - final ComponentFactory componentFactory = new ComponentFactory(); - CoreComponentsRegistry.register(componentFactory); - - // Here we register a Components Registry. - // The one that is generated with the template contains no components - // and just provides you the one from React Native core. - MainComponentsRegistry.register(componentFactory); - - final ReactInstanceManager reactInstanceManager = getReactInstanceManager(); - - ViewManagerRegistry viewManagerRegistry = - new ViewManagerRegistry( - reactInstanceManager.getOrCreateViewManagers(reactApplicationContext)); - - return new FabricJSIModuleProvider( - reactApplicationContext, - componentFactory, - new EmptyReactNativeConfig(), - viewManagerRegistry); - } - }); - return specs; - } - }; - } -} diff --git a/example/android/app/src/main/java/com/example/newarchitecture/components/MainComponentsRegistry.java b/example/android/app/src/main/java/com/example/newarchitecture/components/MainComponentsRegistry.java deleted file mode 100644 index 98ff973..0000000 --- a/example/android/app/src/main/java/com/example/newarchitecture/components/MainComponentsRegistry.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.example.newarchitecture.components; - -import com.facebook.jni.HybridData; -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.fabric.ComponentFactory; -import com.facebook.soloader.SoLoader; - -/** - * Class responsible to load the custom Fabric Components. This class has native methods and needs a - * corresponding C++ implementation/header file to work correctly (already placed inside the jni/ - * folder for you). - * - *

Please note that this class is used ONLY if you opt-in for the New Architecture (see the - * `newArchEnabled` property). Is ignored otherwise. - */ -@DoNotStrip -public class MainComponentsRegistry { - static { - SoLoader.loadLibrary("fabricjni"); - } - - @DoNotStrip private final HybridData mHybridData; - - @DoNotStrip - private native HybridData initHybrid(ComponentFactory componentFactory); - - @DoNotStrip - private MainComponentsRegistry(ComponentFactory componentFactory) { - mHybridData = initHybrid(componentFactory); - } - - @DoNotStrip - public static MainComponentsRegistry register(ComponentFactory componentFactory) { - return new MainComponentsRegistry(componentFactory); - } -} diff --git a/example/android/app/src/main/java/com/example/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java b/example/android/app/src/main/java/com/example/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java deleted file mode 100644 index b30c50e..0000000 --- a/example/android/app/src/main/java/com/example/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.example.newarchitecture.modules; - -import com.facebook.jni.HybridData; -import com.facebook.react.ReactPackage; -import com.facebook.react.ReactPackageTurboModuleManagerDelegate; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.soloader.SoLoader; -import java.util.List; - -/** - * Class responsible to load the TurboModules. This class has native methods and needs a - * corresponding C++ implementation/header file to work correctly (already placed inside the jni/ - * folder for you). - * - *

Please note that this class is used ONLY if you opt-in for the New Architecture (see the - * `newArchEnabled` property). Is ignored otherwise. - */ -public class MainApplicationTurboModuleManagerDelegate - extends ReactPackageTurboModuleManagerDelegate { - - private static volatile boolean sIsSoLibraryLoaded; - - protected MainApplicationTurboModuleManagerDelegate( - ReactApplicationContext reactApplicationContext, List packages) { - super(reactApplicationContext, packages); - } - - protected native HybridData initHybrid(); - - native boolean canCreateTurboModule(String moduleName); - - public static class Builder extends ReactPackageTurboModuleManagerDelegate.Builder { - protected MainApplicationTurboModuleManagerDelegate build( - ReactApplicationContext context, List packages) { - return new MainApplicationTurboModuleManagerDelegate(context, packages); - } - } - - @Override - protected synchronized void maybeLoadOtherSoLibraries() { - if (!sIsSoLibraryLoaded) { - // If you change the name of your application .so file in the Android.mk file, - // make sure you update the name here as well. - SoLoader.loadLibrary("example_appmodules"); - sIsSoLibraryLoaded = true; - } - } -} diff --git a/example/android/app/src/main/jni/Android.mk b/example/android/app/src/main/jni/Android.mk deleted file mode 100644 index 439f7ff..0000000 --- a/example/android/app/src/main/jni/Android.mk +++ /dev/null @@ -1,49 +0,0 @@ -THIS_DIR := $(call my-dir) - -include $(REACT_ANDROID_DIR)/Android-prebuilt.mk - -# If you wish to add a custom TurboModule or Fabric component in your app you -# will have to include the following autogenerated makefile. -# include $(GENERATED_SRC_DIR)/codegen/jni/Android.mk -include $(CLEAR_VARS) - -LOCAL_PATH := $(THIS_DIR) - -# You can customize the name of your application .so file here. -LOCAL_MODULE := example_appmodules - -LOCAL_C_INCLUDES := $(LOCAL_PATH) -LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) - -# If you wish to add a custom TurboModule or Fabric component in your app you -# will have to uncomment those lines to include the generated source -# files from the codegen (placed in $(GENERATED_SRC_DIR)/codegen/jni) -# -# LOCAL_C_INCLUDES += $(GENERATED_SRC_DIR)/codegen/jni -# LOCAL_SRC_FILES += $(wildcard $(GENERATED_SRC_DIR)/codegen/jni/*.cpp) -# LOCAL_EXPORT_C_INCLUDES += $(GENERATED_SRC_DIR)/codegen/jni - -# Here you should add any native library you wish to depend on. -LOCAL_SHARED_LIBRARIES := \ - libfabricjni \ - libfbjni \ - libfolly_futures \ - libfolly_json \ - libglog \ - libjsi \ - libreact_codegen_rncore \ - libreact_debug \ - libreact_nativemodule_core \ - libreact_render_componentregistry \ - libreact_render_core \ - libreact_render_debug \ - libreact_render_graphics \ - librrc_view \ - libruntimeexecutor \ - libturbomodulejsijni \ - libyoga - -LOCAL_CFLAGS := -DLOG_TAG=\"ReactNative\" -fexceptions -frtti -std=c++17 -Wall - -include $(BUILD_SHARED_LIBRARY) diff --git a/example/android/app/src/main/jni/MainApplicationModuleProvider.cpp b/example/android/app/src/main/jni/MainApplicationModuleProvider.cpp deleted file mode 100644 index 0ac23cc..0000000 --- a/example/android/app/src/main/jni/MainApplicationModuleProvider.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "MainApplicationModuleProvider.h" - -#include - -namespace facebook { -namespace react { - -std::shared_ptr MainApplicationModuleProvider( - const std::string moduleName, - const JavaTurboModule::InitParams ¶ms) { - // Here you can provide your own module provider for TurboModules coming from - // either your application or from external libraries. The approach to follow - // is similar to the following (for a library called `samplelibrary`: - // - // auto module = samplelibrary_ModuleProvider(moduleName, params); - // if (module != nullptr) { - // return module; - // } - // return rncore_ModuleProvider(moduleName, params); - return rncore_ModuleProvider(moduleName, params); -} - -} // namespace react -} // namespace facebook diff --git a/example/android/app/src/main/jni/MainApplicationModuleProvider.h b/example/android/app/src/main/jni/MainApplicationModuleProvider.h deleted file mode 100644 index 0fa43fa..0000000 --- a/example/android/app/src/main/jni/MainApplicationModuleProvider.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include -#include - -#include - -namespace facebook { -namespace react { - -std::shared_ptr MainApplicationModuleProvider( - const std::string moduleName, - const JavaTurboModule::InitParams ¶ms); - -} // namespace react -} // namespace facebook diff --git a/example/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.cpp b/example/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.cpp deleted file mode 100644 index dbbdc3d..0000000 --- a/example/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "MainApplicationTurboModuleManagerDelegate.h" -#include "MainApplicationModuleProvider.h" - -namespace facebook { -namespace react { - -jni::local_ref -MainApplicationTurboModuleManagerDelegate::initHybrid( - jni::alias_ref) { - return makeCxxInstance(); -} - -void MainApplicationTurboModuleManagerDelegate::registerNatives() { - registerHybrid({ - makeNativeMethod( - "initHybrid", MainApplicationTurboModuleManagerDelegate::initHybrid), - makeNativeMethod( - "canCreateTurboModule", - MainApplicationTurboModuleManagerDelegate::canCreateTurboModule), - }); -} - -std::shared_ptr -MainApplicationTurboModuleManagerDelegate::getTurboModule( - const std::string name, - const std::shared_ptr jsInvoker) { - // Not implemented yet: provide pure-C++ NativeModules here. - return nullptr; -} - -std::shared_ptr -MainApplicationTurboModuleManagerDelegate::getTurboModule( - const std::string name, - const JavaTurboModule::InitParams ¶ms) { - return MainApplicationModuleProvider(name, params); -} - -bool MainApplicationTurboModuleManagerDelegate::canCreateTurboModule( - std::string name) { - return getTurboModule(name, nullptr) != nullptr || - getTurboModule(name, {.moduleName = name}) != nullptr; -} - -} // namespace react -} // namespace facebook diff --git a/example/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.h b/example/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.h deleted file mode 100644 index 9dc2af6..0000000 --- a/example/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.h +++ /dev/null @@ -1,38 +0,0 @@ -#include -#include - -#include -#include - -namespace facebook { -namespace react { - -class MainApplicationTurboModuleManagerDelegate - : public jni::HybridClass< - MainApplicationTurboModuleManagerDelegate, - TurboModuleManagerDelegate> { - public: - // Adapt it to the package you used for your Java class. - static constexpr auto kJavaDescriptor = - "Lcom/example/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate;"; - - static jni::local_ref initHybrid(jni::alias_ref); - - static void registerNatives(); - - std::shared_ptr getTurboModule( - const std::string name, - const std::shared_ptr jsInvoker) override; - std::shared_ptr getTurboModule( - const std::string name, - const JavaTurboModule::InitParams ¶ms) override; - - /** - * Test-only method. Allows user to verify whether a TurboModule can be - * created by instances of this class. - */ - bool canCreateTurboModule(std::string name); -}; - -} // namespace react -} // namespace facebook diff --git a/example/android/app/src/main/jni/MainComponentsRegistry.cpp b/example/android/app/src/main/jni/MainComponentsRegistry.cpp deleted file mode 100644 index 8f7edff..0000000 --- a/example/android/app/src/main/jni/MainComponentsRegistry.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "MainComponentsRegistry.h" - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -MainComponentsRegistry::MainComponentsRegistry(ComponentFactory *delegate) {} - -std::shared_ptr -MainComponentsRegistry::sharedProviderRegistry() { - auto providerRegistry = CoreComponentsRegistry::sharedProviderRegistry(); - - // Custom Fabric Components go here. You can register custom - // components coming from your App or from 3rd party libraries here. - // - // providerRegistry->add(concreteComponentDescriptorProvider< - // AocViewerComponentDescriptor>()); - return providerRegistry; -} - -jni::local_ref -MainComponentsRegistry::initHybrid( - jni::alias_ref, - ComponentFactory *delegate) { - auto instance = makeCxxInstance(delegate); - - auto buildRegistryFunction = - [](EventDispatcher::Weak const &eventDispatcher, - ContextContainer::Shared const &contextContainer) - -> ComponentDescriptorRegistry::Shared { - auto registry = MainComponentsRegistry::sharedProviderRegistry() - ->createComponentDescriptorRegistry( - {eventDispatcher, contextContainer}); - - auto mutableRegistry = - std::const_pointer_cast(registry); - - mutableRegistry->setFallbackComponentDescriptor( - std::make_shared( - ComponentDescriptorParameters{ - eventDispatcher, contextContainer, nullptr})); - - return registry; - }; - - delegate->buildRegistryFunction = buildRegistryFunction; - return instance; -} - -void MainComponentsRegistry::registerNatives() { - registerHybrid({ - makeNativeMethod("initHybrid", MainComponentsRegistry::initHybrid), - }); -} - -} // namespace react -} // namespace facebook diff --git a/example/android/app/src/main/jni/MainComponentsRegistry.h b/example/android/app/src/main/jni/MainComponentsRegistry.h deleted file mode 100644 index 23a9cac..0000000 --- a/example/android/app/src/main/jni/MainComponentsRegistry.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -class MainComponentsRegistry - : public facebook::jni::HybridClass { - public: - // Adapt it to the package you used for your Java class. - constexpr static auto kJavaDescriptor = - "Lcom/example/newarchitecture/components/MainComponentsRegistry;"; - - static void registerNatives(); - - MainComponentsRegistry(ComponentFactory *delegate); - - private: - static std::shared_ptr - sharedProviderRegistry(); - - static jni::local_ref initHybrid( - jni::alias_ref, - ComponentFactory *delegate); -}; - -} // namespace react -} // namespace facebook diff --git a/example/android/app/src/main/jni/OnLoad.cpp b/example/android/app/src/main/jni/OnLoad.cpp deleted file mode 100644 index c569b6e..0000000 --- a/example/android/app/src/main/jni/OnLoad.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include "MainApplicationTurboModuleManagerDelegate.h" -#include "MainComponentsRegistry.h" - -JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { - return facebook::jni::initialize(vm, [] { - facebook::react::MainApplicationTurboModuleManagerDelegate:: - registerNatives(); - facebook::react::MainComponentsRegistry::registerNatives(); - }); -} diff --git a/example/android/app/src/main/res/drawable/rn_edit_text_material.xml b/example/android/app/src/main/res/drawable/rn_edit_text_material.xml index f35d996..73b37e4 100644 --- a/example/android/app/src/main/res/drawable/rn_edit_text_material.xml +++ b/example/android/app/src/main/res/drawable/rn_edit_text_material.xml @@ -20,7 +20,7 @@ android:insetBottom="@dimen/abc_edit_text_inset_bottom_material"> -