├── .eslintignore ├── .eslintrc.js ├── .github └── workflows │ └── publish.yml ├── .gitignore ├── .husky ├── commit-msg ├── pre-commit └── pre-push ├── .npmignore ├── .prettierrc.js ├── .vscode └── settings.json ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── assets ├── barChart.gif ├── barChartWithLegends.png ├── charts.gif ├── lineChart.gif ├── lineChartWithLegends.png └── reactGraph.gif ├── babel.config.js ├── example ├── .buckconfig ├── .bundle │ └── config ├── .gitignore ├── .node-version ├── .prettierrc.js ├── .ruby-version ├── .watchmanconfig ├── android │ ├── app │ │ ├── _BUCK │ │ ├── build.gradle │ │ ├── build_defs.bzl │ │ ├── debug.keystore │ │ ├── proguard-rules.pro │ │ └── src │ │ │ ├── debug │ │ │ ├── AndroidManifest.xml │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── rn_example │ │ │ │ └── ReactNativeFlipper.java │ │ │ └── main │ │ │ ├── AndroidManifest.xml │ │ │ ├── java │ │ │ └── com │ │ │ │ └── rn_example │ │ │ │ ├── MainActivity.java │ │ │ │ ├── MainApplication.java │ │ │ │ └── newarchitecture │ │ │ │ ├── MainApplicationReactNativeHost.java │ │ │ │ ├── components │ │ │ │ └── MainComponentsRegistry.java │ │ │ │ └── modules │ │ │ │ └── MainApplicationTurboModuleManagerDelegate.java │ │ │ ├── jni │ │ │ ├── CMakeLists.txt │ │ │ ├── MainApplicationModuleProvider.cpp │ │ │ ├── MainApplicationModuleProvider.h │ │ │ ├── MainApplicationTurboModuleManagerDelegate.cpp │ │ │ ├── MainApplicationTurboModuleManagerDelegate.h │ │ │ ├── MainComponentsRegistry.cpp │ │ │ ├── MainComponentsRegistry.h │ │ │ └── OnLoad.cpp │ │ │ └── res │ │ │ ├── drawable │ │ │ └── rn_edit_text_material.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 │ │ │ └── values │ │ │ ├── strings.xml │ │ │ └── styles.xml │ ├── build.gradle │ ├── gradle.properties │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ └── settings.gradle ├── app.json ├── babel.config.js ├── index.js ├── ios │ ├── .xcode.env │ ├── Podfile │ ├── rn_example.xcodeproj │ │ ├── project.pbxproj │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ └── rn_example.xcscheme │ ├── rn_example.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ ├── rn_example │ │ ├── AppDelegate.h │ │ ├── AppDelegate.mm │ │ ├── Images.xcassets │ │ │ ├── AppIcon.appiconset │ │ │ │ └── Contents.json │ │ │ └── Contents.json │ │ ├── Info.plist │ │ ├── LaunchScreen.storyboard │ │ └── main.m │ └── rn_exampleTests │ │ ├── Info.plist │ │ └── rn_exampleTests.m ├── metro.config.js ├── package.json ├── src │ ├── App.tsx │ ├── constants │ │ ├── StaticData.ts │ │ ├── Strings.ts │ │ └── index.ts │ └── theme │ │ ├── ApplicationStyles.ts │ │ ├── Colors.ts │ │ ├── Metrics.tsx │ │ └── index.ts └── tsconfig.json ├── package.json ├── src ├── components │ ├── bar-chart │ │ ├── BarChart.tsx │ │ ├── BarChartStyles.ts │ │ ├── BarChartTypes.ts │ │ ├── components │ │ │ ├── index.ts │ │ │ ├── xaxis-label │ │ │ │ ├── XAxisLabels.tsx │ │ │ │ ├── XAxisLabelsTypes.ts │ │ │ │ └── index.ts │ │ │ ├── yaxis-label │ │ │ │ ├── YAxisLabels.tsx │ │ │ │ ├── YAxisLabelsPropsTypes.ts │ │ │ │ └── index.ts │ │ │ └── yref-lines │ │ │ │ ├── YRefLines.tsx │ │ │ │ ├── YRefLinesTypes.ts │ │ │ │ └── index.ts │ │ ├── index.ts │ │ └── useBarChart.ts │ ├── index.ts │ ├── line-chart │ │ ├── LineChart.tsx │ │ ├── LineChartStyles.ts │ │ ├── LineChartTypes.ts │ │ ├── components │ │ │ ├── index.ts │ │ │ ├── x-axis-labels │ │ │ │ ├── XAxisLabelTypes.ts │ │ │ │ ├── XAxisLabels.tsx │ │ │ │ └── index.ts │ │ │ ├── x-axis-legend │ │ │ │ ├── XAxisLegend.tsx │ │ │ │ ├── XAxisLegendStyles.ts │ │ │ │ ├── XAxisLegendTypes.ts │ │ │ │ └── index.ts │ │ │ ├── y-axis-labels │ │ │ │ ├── YAxisLabels.tsx │ │ │ │ ├── YAxisLabelsTypes.ts │ │ │ │ └── index.ts │ │ │ ├── y-axis-legend │ │ │ │ ├── YAxisLegend.tsx │ │ │ │ ├── YAxisLegendStyles.ts │ │ │ │ ├── YAxisLegendTypes.ts │ │ │ │ └── index.ts │ │ │ └── y-ref-lines │ │ │ │ ├── YRefLines.tsx │ │ │ │ ├── YRefLinesTypes.ts │ │ │ │ └── index.ts │ │ ├── index.ts │ │ └── useLineChart.ts │ └── tooltip │ │ ├── Tooltip.tsx │ │ ├── TooltipTypes.ts │ │ ├── index.ts │ │ ├── useTooltip.ts │ │ └── useTooltipUtils.ts ├── constants │ ├── Constants.ts │ └── index.ts ├── hooks │ ├── index.ts │ └── useDefaultFont.ts ├── index.ts ├── theme │ ├── Colors.ts │ ├── Metrics.tsx │ └── index.ts └── utils │ ├── CommonUtils.ts │ └── index.ts └── tsconfig.json /.eslintignore: -------------------------------------------------------------------------------- 1 | **/node_modules 2 | example/ 3 | lib/ 4 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | const OFF = 0; 2 | const WARN = 1; 3 | const ERROR = 2; 4 | 5 | module.exports = { 6 | root: true, 7 | extends: [ 8 | '@react-native-community', 9 | 'prettier', 10 | 'plugin:react-native/all', 11 | 'plugin:prettier/recommended', // https://github.com/prettier/eslint-plugin-prettier#recommended-configuration 12 | 'eslint:recommended', 13 | 'plugin:react/recommended', 14 | 'plugin:react-hooks/recommended', 15 | 'plugin:import/errors', 16 | 'plugin:import/warnings', 17 | '@react-native-community/eslint-config', 18 | 'eslint-config-prettier' 19 | ], 20 | parser: '@typescript-eslint/parser', 21 | parserOptions: { 22 | ecmaVersion: 2018, 23 | sourceType: 'module', 24 | jsx: true, 25 | tsconfigRootDir: __dirname 26 | }, 27 | ignorePatterns: ['.eslintrc.js'], 28 | plugins: [ 29 | '@typescript-eslint', 30 | 'eslint-comments', 31 | 'react', 32 | 'react-hooks', 33 | 'react-native', 34 | '@react-native-community', 35 | 'prettier', 36 | 'jest', 37 | 'import' 38 | ], 39 | settings: { 40 | 'import/resolver': { 41 | typescript: { 42 | alwaysTryTypes: true, // always try to resolve types under `@types` directory even it doesn't contain any source code, like `@types/unist` 43 | 44 | // Choose from one of the "project" configs below or omit to use /tsconfig.json by default 45 | 46 | // use /path/to/folder/tsconfig.json 47 | project: 'tsconfig.json' 48 | } 49 | } 50 | }, 51 | // Map from global var to bool specifying if it can be redefined 52 | globals: { 53 | __DEV__: true, 54 | __dirname: false, 55 | __fbBatchedBridgeConfig: false, 56 | alert: false, 57 | cancelAnimationFrame: false, 58 | cancelIdleCallback: false, 59 | clearImmediate: true, 60 | clearInterval: false, 61 | clearTimeout: false, 62 | console: false, 63 | document: false, 64 | escape: false, 65 | Event: false, 66 | EventTarget: false, 67 | exports: false, 68 | fetch: false, 69 | FormData: false, 70 | global: false, 71 | Map: true, 72 | module: false, 73 | navigator: false, 74 | process: false, 75 | Promise: true, 76 | requestAnimationFrame: true, 77 | requestIdleCallback: true, 78 | require: false, 79 | Set: true, 80 | setImmediate: true, 81 | setInterval: false, 82 | setTimeout: false, 83 | window: false, 84 | XMLHttpRequest: false 85 | }, 86 | rules: { 87 | 'prettier/prettier': [ 88 | ERROR, 89 | {}, 90 | { 91 | usePrettierrc: true 92 | } 93 | ], 94 | // General 95 | indent: [ 96 | OFF, 97 | 2, 98 | { 99 | SwitchCase: 1, 100 | VariableDeclarator: 1, 101 | outerIIFEBody: 1, 102 | FunctionDeclaration: { 103 | parameters: 1, 104 | body: 1 105 | }, 106 | FunctionExpression: { 107 | parameters: 1, 108 | body: 1 109 | }, 110 | flatTernaryExpressions: true, 111 | offsetTernaryExpressions: true 112 | } 113 | ], 114 | // general 115 | 'global-require': OFF, 116 | 'no-plusplus': OFF, 117 | 'no-cond-assign': OFF, 118 | 'max-classes-per-file': [ERROR, 10], 119 | 'no-shadow': OFF, 120 | 'no-undef': OFF, 121 | 'no-bitwise': OFF, 122 | 'no-param-reassign': OFF, 123 | 'no-use-before-define': OFF, 124 | 'linebreak-style': [ERROR, 'unix'], 125 | semi: [ERROR, 'always'], 126 | 'comma-dangle': [ 127 | ERROR, 128 | { 129 | arrays: 'never', 130 | objects: 'never', 131 | imports: 'never', 132 | exports: 'never', 133 | functions: 'ignore' 134 | } 135 | ], 136 | 'object-curly-spacing': [ERROR, 'always'], 137 | 'eol-last': [ERROR, 'always'], 138 | 'no-console': OFF, 139 | 'no-restricted-syntax': [ 140 | WARN, 141 | { 142 | selector: 143 | "CallExpression[callee.object.name='console'][callee.property.name!=/^(warn|error|info|trace|disableYellowBox|tron)$/]", 144 | message: 'Unexpected property on console object was called' 145 | } 146 | ], 147 | 'require-jsdoc': [ 148 | WARN, 149 | { 150 | require: { 151 | FunctionDeclaration: true, 152 | MethodDefinition: true, 153 | ClassDeclaration: true, 154 | ArrowFunctionExpression: true, 155 | FunctionExpression: true 156 | } 157 | } 158 | ], 159 | eqeqeq: [WARN, 'always'], 160 | quotes: [ERROR, 'single', { avoidEscape: true, allowTemplateLiterals: false }], 161 | // typescript 162 | '@typescript-eslint/no-shadow': [ERROR], 163 | '@typescript-eslint/no-use-before-define': [ERROR], 164 | '@typescript-eslint/no-unused-vars': ERROR, 165 | '@typescript-eslint/consistent-type-definitions': [ERROR, 'interface'], 166 | '@typescript-eslint/indent': [ 167 | OFF, 168 | 2, 169 | { 170 | SwitchCase: 1, 171 | VariableDeclarator: 1, 172 | outerIIFEBody: 1, 173 | FunctionDeclaration: { 174 | parameters: 1, 175 | body: 1 176 | }, 177 | FunctionExpression: { 178 | parameters: 1, 179 | body: 1 180 | }, 181 | flatTernaryExpressions: true, 182 | offsetTernaryExpressions: true 183 | } 184 | ], 185 | // imports 186 | 'import/extensions': OFF, 187 | 'import/prefer-default-export': OFF, 188 | 'import/no-cycle': OFF, 189 | 'import/order': [ 190 | ERROR, 191 | { 192 | groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index', 'object', 'type'], 193 | alphabetize: { 194 | order: 'asc', 195 | caseInsensitive: true 196 | }, 197 | warnOnUnassignedImports: true 198 | } 199 | ], 200 | 'import/no-unresolved': [ERROR, { commonjs: true, amd: true }], 201 | 'import/named': ERROR, 202 | 'import/namespace': ERROR, 203 | 'import/default': ERROR, 204 | 'import/export': ERROR, 205 | 'import/no-extraneous-dependencies': [ERROR, { devDependencies: true }], 206 | // react hooks 207 | 'react-hooks/exhaustive-deps': ERROR, 208 | 'react-hooks/rules-of-hooks': ERROR, 209 | // react 210 | 'react/jsx-props-no-spreading': OFF, 211 | 'react/jsx-filename-extension': [ERROR, { extensions: ['.js', '.jsx', '.ts', '.tsx'] }], 212 | 'react/no-unescaped-entities': [ERROR, { forbid: ['>', '"', '}'] }], 213 | 'react/prop-types': [ERROR, { ignore: ['action', 'dispatch', 'nav', 'navigation'] }], 214 | 'react/display-name': OFF, 215 | 'react/jsx-boolean-value': ERROR, 216 | 'react/jsx-no-undef': ERROR, 217 | 'react/jsx-uses-react': ERROR, 218 | 'react/jsx-sort-props': [ 219 | ERROR, 220 | { 221 | callbacksLast: true, 222 | shorthandFirst: true, 223 | ignoreCase: true, 224 | noSortAlphabetically: true 225 | } 226 | ], 227 | 'react/jsx-pascal-case': ERROR, 228 | 'react/no-children-prop': OFF, 229 | // react-native specific rules 230 | 'react-native/no-unused-styles': ERROR, 231 | 'react-native/no-inline-styles': ERROR, 232 | 'react-native/no-color-literals': ERROR, 233 | 'react-native/no-raw-text': ERROR 234 | } 235 | }; 236 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: '🚀 Publish' 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | release: 10 | name: 🚀 Publish 11 | runs-on: macos-11 12 | steps: 13 | - name: 📚 checkout 14 | uses: actions/checkout@v2.4.2 15 | - name: 🟢 node 16 | uses: actions/setup-node@v3.3.0 17 | with: 18 | node-version: 16 19 | registry-url: https://registry.npmjs.org 20 | - name: 🚀 Build & Publish 21 | run: yarn install && yarn build && yarn publish --access public 22 | env: 23 | NODE_AUTH_TOKEN: ${{secrets.NPM_AUTH_TOKEN}} 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | 24 | # Android/IntelliJ 25 | # 26 | build/ 27 | .idea 28 | .gradle 29 | local.properties 30 | *.iml 31 | 32 | # node.js 33 | # 34 | node_modules/ 35 | npm-debug.log 36 | yarn-error.log* 37 | yarn.lock 38 | 39 | # BUCK 40 | buck-out/ 41 | \.buckd/ 42 | *.keystore 43 | !debug.keystore 44 | 45 | # fastlane 46 | # 47 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 48 | # screenshots whenever they are needed. 49 | # For more information about the recommended setup visit: 50 | # https://docs.fastlane.tools/best-practices/source-control/ 51 | 52 | */fastlane/report.xml 53 | */fastlane/Preview.html 54 | */fastlane/screenshots 55 | 56 | # Bundle artifact 57 | *.jsbundle 58 | 59 | # Ruby / CocoaPods 60 | /ios/Pods/ 61 | /vendor/bundle/ 62 | 63 | # generated 64 | lib 65 | 66 | # vscode settings 67 | .vscode/ 68 | 69 | # husky settings 70 | .husky/ -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx commitlint --edit $1 5 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx lint-staged 5 | -------------------------------------------------------------------------------- /.husky/pre-push: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx build 5 | npx test -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .github/ 2 | example/ 3 | assets/ 4 | .eslintignore 5 | .eslintrc 6 | CONTRIBUTING.md 7 | babel.config.js 8 | .buckconfig 9 | jest-setup.js 10 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | useTabs: false, 3 | printWidth: 100, 4 | tabWidth: 2, 5 | singleQuote: true, 6 | trailingComma: 'none', 7 | semi: true, 8 | quoteProps: 'as-needed', 9 | bracketSpacing: true, 10 | arrowParens: 'always', 11 | }; -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "eslint.alwaysShowStatus": true, 3 | "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"], 4 | "editor.formatOnSave": true, 5 | "editor.formatOnPaste": true, 6 | "javascript.validate.enable": true, 7 | "typescript.validate.enable": true, 8 | "json.format.enable": true, 9 | "editor.tabSize": 2, 10 | "editor.defaultFormatter": "esbenp.prettier-vscode", 11 | "[javascript]": { 12 | "editor.formatOnSave": true, 13 | "editor.formatOnPaste": true, 14 | "editor.defaultFormatter": "esbenp.prettier-vscode" 15 | }, 16 | "[javascriptreact]": { 17 | "editor.formatOnSave": true, 18 | "editor.formatOnPaste": true, 19 | "editor.defaultFormatter": "esbenp.prettier-vscode" 20 | }, 21 | "[typescript]": { 22 | "editor.formatOnSave": true, 23 | "editor.formatOnPaste": true, 24 | "editor.defaultFormatter": "esbenp.prettier-vscode" 25 | }, 26 | "[typescriptreact]": { 27 | "editor.formatOnSave": true, 28 | "editor.formatOnPaste": true, 29 | "editor.defaultFormatter": "esbenp.prettier-vscode" 30 | }, 31 | "[json]": { 32 | "editor.formatOnSave": true, 33 | "editor.formatOnPaste": true, 34 | "editor.defaultFormatter": "vscode.json-language-features" 35 | }, 36 | "editor.codeActionsOnSave": { 37 | "source.fixAll": "explicit", 38 | "source.fixAll.eslint": "explicit" 39 | }, 40 | "workbench.editor.enablePreview": false, 41 | "workbench.editor.enablePreviewFromQuickOpen": false, 42 | "docwriter.style": "JSDoc" 43 | } 44 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We welcome code changes that improve this library or fix a problem, and please make sure to follow all best practices and test all the changes/fixes before committing and creating a pull request. 🚀 🚀 4 | 5 | ### Committing and Pushing Changes 6 | 7 | Commit messages should be formatted as: 8 | 9 | ``` 10 | [optional scope]: 11 | 12 | [optional body] 13 | 14 | [optional footer] 15 | ``` 16 | 17 | Where type can be one of the following: 18 | 19 | - feat 20 | - fix 21 | - docs 22 | - chore 23 | - style 24 | - refactor 25 | - test 26 | 27 | and an optional scope can be a component 28 | 29 | ``` 30 | docs: update contributing guide 31 | ``` 32 | 33 | ``` 34 | fix(TicketId/Component): layout flicker issue 35 | ``` 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Simform Solutions 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # react-native-graph-kit 4 | 5 | [![@shopify/react-native-skia](https://img.shields.io/badge/%40shopify%2Freact--native--skia-0.1.228-blue.svg?style=flat-square)](https://github.com/Shopify/react-native-skia) 6 | [![react-native-graph-kit on npm](https://img.shields.io/npm/v/react-native-graph-kit?style=flat-square&label=npm&color=blue)](https://www.npmjs.com/package/react-native-graph-kit) [![npm downloads](https://img.shields.io/npm/dm/react-native-graph-kit.svg?style=flat-square)](https://www.npmjs.com/package/react-native-graph-kit) [![Android](https://img.shields.io/badge/Platform-Android-green?logo=android&style=flat-square)](https://www.android.com) [![iOS](https://img.shields.io/badge/Platform-iOS-green?logo=apple&style=flat-square)](https://developer.apple.com/ios) [![MIT](https://img.shields.io/badge/License-MIT-green?style=flat-square)](https://opensource.org/licenses/MIT) 7 | 8 | --- 9 | 10 | **React Native Graph Kit** is a powerful library that is built using @shopify/react-native-skia to provide LineChart and BarChart components with interactive tooltips for your React Native applications. With this library, you can effortlessly visualize your data in a clean and intuitive manner, making it easier than ever for users to understand complex datasets. 11 | 12 | ℹ️ **Compatibility Notice:** This library is designed to work seamlessly with `@shopify/react-native-skia` version `<=0.1.228`. Make sure to use this version for optimal compatibility. 13 | 14 | - It also provides an example app and a detailed usage overview of both the components. 15 | - Both the available components are fully Android and iOS compatible. 16 | 17 | ## 🎬 Preview 18 | 19 | | LineChart | BarChart | 20 | | --------------------------------------------------------------- | -------------------------------------------------------------- | 21 | | | | 22 | 23 | ## Quick Access 24 | 25 | [Installation](#installation) | [Charts](#charts) | [Properties](#properties) | [Example](#example) | [License](#license) 26 | 27 | # Installation 28 | 29 | ##### 1. Install library and @shopify/react-native-skia 30 | 31 | ```bash 32 | npm install react-native-graph-kit @shopify/react-native-skia 33 | ``` 34 | 35 | ###### --- or --- 36 | 37 | ```bash 38 | yarn add react-native-graph-kit @shopify/react-native-skia 39 | ``` 40 | 41 | ##### 2. Install cocoapods in the ios project 42 | 43 | ```bash 44 | cd ios && pod install 45 | ``` 46 | 47 | And you are good to begin. 48 | 49 | --- 50 | 51 | # Charts 52 | 53 | | BarChart | LineChart | 54 | | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | 55 | | | | 56 | | | 57 | 58 | - LineChart: Create elegant line charts to showcase trends and patterns in your data. 59 | - BarChart: Display data using visually appealing bar charts, making comparisons at a glance. 60 | 61 | ### ChartDataType 62 | 63 | ```jsx 64 | type ChartDataType = { 65 | xAxis: { 66 | labels: string[] 67 | }, 68 | yAxis: { 69 | datasets: number[] 70 | } 71 | }; 72 | ``` 73 | 74 | ### ChartDataFormat 75 | 76 | ```jsx 77 | const data = { 78 | xAxis: { 79 | labels: [ 80 | 'Alice', 81 | 'Bob', 82 | 'Charlie', 83 | 'Liam', 84 | 'Mia', 85 | 'Nora', 86 | 'Oliver', 87 | 'Penelope', 88 | 'Quinn', 89 | 'Ryan', 90 | 'Sophia' 91 | ] 92 | }, 93 | yAxis: { 94 | datasets: [230, 75, 100, 500, 387, 655, 30, 60, 400, 500, 687] 95 | } 96 | }; 97 | ``` 98 | 99 | #### Usage 100 | 101 | ##### Basic Example 102 | 103 | ```jsx 104 | import React from 'react'; 105 | import { SafeAreaView, StyleSheet, View } from 'react-native'; 106 | import { BarChart, LineChart } from 'react-native-graph-kit'; 107 | 108 | const data = { 109 | xAxis: { 110 | labels: [ 111 | 'Alice', 112 | 'Bob', 113 | 'Charlie', 114 | 'Liam', 115 | 'Mia', 116 | 'Nora', 117 | 'Oliver', 118 | 'Penelope', 119 | 'Quinn', 120 | 'Ryan', 121 | 'Sophia' 122 | ] 123 | }, 124 | yAxis: { 125 | datasets: [120, 350, 400, 70, 87, 655, 10, 20, 400, 70, 87] 126 | } 127 | }; 128 | 129 | const App = () => ( 130 | 131 | 132 | 140 | 141 | 142 | 143 | 144 | 145 | ); 146 | 147 | const styles = StyleSheet.create({ 148 | screen: { 149 | flex: 1 150 | }, 151 | chartContainer: { 152 | flex: 1, 153 | borderRadius: 10, 154 | borderWidth: 0.5, 155 | borderColor: 'lightgrey', 156 | padding: 10, 157 | margin: 10, 158 | shadowColor: 'lightgrey', 159 | shadowOpacity: 1, 160 | backgroundColor: 'white', 161 | shadowOffset: { 162 | height: 6, 163 | width: 5 164 | } 165 | } 166 | }); 167 | 168 | export default App; 169 | ``` 170 | 171 | --- 172 | 173 | # Properties 174 | 175 | ### Chart Props 176 | 177 | | Prop | Default | Type | Description | BarChart | LineChart | 178 | | :---------------------- | :---------- | :------------ | :--------------------------------------------------- | -------- | --------- | 179 | | **chartData\*** | null | ChartDataType | Data to plot graphs | ✔️ | ✔️ | 180 | | chartHeight | 500 | number | Height of chart in BarChart | ✔️ | ⤫ | 181 | | showLines | true | boolean | Control visibility of Y Axis Ref lines on the chart | ✔️ | ✔️ | 182 | | lineHeight | 2 | number | Height of horizontal grid lines in BarChart | ✔️ | ⤫ | 183 | | lineWidth | 3 | number | The line width value of LineChart | ⤫ | ✔️ | 184 | | lineColor | #DE5E69 | ColorValue | The line color of LineChart | ⤫ | ✔️ | 185 | | barWidth | 20 | number | The width of the bars in BarChart | ✔️ | ⤫ | 186 | | barColor | #DE5E69 | ColorValue | The color of the bars in BarChart | ✔️ | ⤫ | 187 | | barRadius | 0 | number | The borderRadius of the bars in BarChart from top | ✔️ | ⤫ | 188 | | barGap | 50 | number | X Axis length covered by bars | ✔️ | ⤫ | 189 | | labelSize | 18 | number | The fontsize of labels on the chart | ✔️ | ✔️ | 190 | | labelColor | #000000 | ColorValue | The font color of chart labels | ✔️ | ✔️ | 191 | | labelFontFamily | System Font | ColorValue | The font path that will be applied to chart labels | ✔️ | ✔️ | 192 | | horizontalGridLineColor | #D3D3D3 | Color | The Ref lines color | ✔️ | ✔️ | 193 | | yAxisMin | 0 | number | The minimum value for the YAxis Plotting | ✔️ | ✔️ | 194 | | yAxisMax | auto | number | The maximum value for the YAxis Plotting | ✔️ | ✔️ | 195 | | initialDistance | 10 | number | The initial distance of chart from the Y Axis Labels | ✔️ | ✔️ | 196 | | xAxisLength | auto | number | Manual distance between x Axis Plotting | ⤫ | ✔️ | 197 | | verticalLabel | false | boolean | Handle rotation of X-Axis Labels | ✔️ | ✔️ | 198 | | verticalLabelHeight | auto | number | Desired height of the X-Axis | ⤫ | ✔️ | 199 | | chartBackgroundColor | #FFFFFF | Color | Chart background color | ✔️ | ✔️ | 200 | | xAxisLegend | undefined | string | The X Axis Legend Value | ✔️ | ✔️ | 201 | | yAxisLegend | undefined | string | The Y Axis Legend Value | ✔️ | ✔️ | 202 | | xLegendStyles | Default | TextStyle | X Axis Legend styles | ✔️ | ✔️ | 203 | | yLegendStyles | Default | TextStyle | Y Axis Legend styles | ✔️ | ✔️ | 204 | 205 | --- 206 | 207 | ### Tooltip Props 208 | 209 | | Prop | Default | Type | Description | BarChart | LineChart | 210 | | :----------------------- | :------ | :------ | :-------------------------------------- | -------- | --------- | 211 | | displayTooltip | false | boolean | Flag to handle tooltip visibility | ✔️ | ✔️ | 212 | | toolTipLabelFontSize | 12 | number | Font size | ✔️ | ✔️ | 213 | | toolTipColor | #FF0000 | string | Tooltip color | ✔️ | ✔️ | 214 | | toolTipDataColor | #FFFFFF | string | Tooltip data color | ✔️ | ✔️ | 215 | | toolTipHorizontalPadding | 20 | number | Tooltip padding | ✔️ | ✔️ | 216 | | toolTipFadeOutDuration | 4000 | number | Duration in ms to fade out tooltip | ✔️ | ✔️ | 217 | | circularPointerColor | #000000 | string | Color of circular pointer for LineChart | ⤫ | ✔️ | 218 | 219 | --- 220 | 221 | # Example 222 | 223 | A full working example project is here [Example](./example/src/App.tsx) 224 | 225 | ```sh 226 | yarn 227 | yarn example ios // For ios 228 | yarn example android // For Android 229 | ``` 230 | 231 | # TODO 232 | 233 | - [ ] Add option to enable Parametric Curve 234 | 235 | ## Find this library useful? ❤️ 236 | 237 | Support it by joining [stargazers](https://github.com/SimformSolutionsPvtLtd/react-native-graph-kit/stargazers) for this repository.⭐ 238 | 239 | ## Bugs / Feature requests / Feedbacks 240 | 241 | For bugs, feature requests, and discussion please use [GitHub Issues](https://github.com/SimformSolutionsPvtLtd/react-native-graph-kit/issues/new?labels=bug&late=BUG_REPORT.md&title=%5BBUG%5D%3A), [GitHub New Feature](https://github.com/SimformSolutionsPvtLtd/react-native-graph-kit/issues/new?labels=enhancement&late=FEATURE_REQUEST.md&title=%5BFEATURE%5D%3A), [GitHub Feedback](https://github.com/SimformSolutionsPvtLtd/react-native-graph-kit/issues/new?labels=enhancement&late=FEATURE_REQUEST.md&title=%5BFEEDBACK%5D%3A) 242 | 243 | ## 🤝 How to Contribute 244 | 245 | We'd love to have you improve this library or fix a problem 💪 246 | Check out our [Contributing Guide](CONTRIBUTING.md) for ideas on contributing. 247 | 248 | ## Awesome Mobile Libraries 249 | 250 | - Check out our other [available awesome mobile libraries](https://github.com/SimformSolutionsPvtLtd/Awesome-Mobile-Libraries) 251 | 252 | ## License 253 | 254 | - [MIT License](./LICENSE) 255 | -------------------------------------------------------------------------------- /assets/barChart.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/assets/barChart.gif -------------------------------------------------------------------------------- /assets/barChartWithLegends.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/assets/barChartWithLegends.png -------------------------------------------------------------------------------- /assets/charts.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/assets/charts.gif -------------------------------------------------------------------------------- /assets/lineChart.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/assets/lineChart.gif -------------------------------------------------------------------------------- /assets/lineChartWithLegends.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/assets/lineChartWithLegends.png -------------------------------------------------------------------------------- /assets/reactGraph.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/assets/reactGraph.gif -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /example/.buckconfig: -------------------------------------------------------------------------------- 1 | 2 | [android] 3 | target = Google Inc.:Google APIs:23 4 | 5 | [maven_repositories] 6 | central = https://repo1.maven.org/maven2 7 | -------------------------------------------------------------------------------- /example/.bundle/config: -------------------------------------------------------------------------------- 1 | BUNDLE_PATH: "vendor/bundle" 2 | BUNDLE_FORCE_RUBY_PLATFORM: 1 3 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | ios/.xcode.env.local 24 | 25 | # Android/IntelliJ 26 | # 27 | build/ 28 | .idea 29 | .gradle 30 | local.properties 31 | *.iml 32 | *.hprof 33 | .cxx/ 34 | 35 | # node.js 36 | # 37 | node_modules/ 38 | npm-debug.log 39 | yarn-error.log 40 | yarn.lock 41 | 42 | # BUCK 43 | buck-out/ 44 | \.buckd/ 45 | *.keystore 46 | !debug.keystore 47 | 48 | # fastlane 49 | # 50 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 51 | # screenshots whenever they are needed. 52 | # For more information about the recommended setup visit: 53 | # https://docs.fastlane.tools/best-practices/source-control/ 54 | 55 | **/fastlane/report.xml 56 | **/fastlane/Preview.html 57 | **/fastlane/screenshots 58 | **/fastlane/test_output 59 | 60 | # Bundle artifact 61 | *.jsbundle 62 | 63 | # Ruby / CocoaPods 64 | /ios/Pods/ 65 | /vendor/bundle/ 66 | /ios/Podfile.lock -------------------------------------------------------------------------------- /example/.node-version: -------------------------------------------------------------------------------- 1 | 16 2 | -------------------------------------------------------------------------------- /example/.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | arrowParens: 'avoid', 3 | bracketSameLine: true, 4 | bracketSpacing: true, 5 | singleQuote: true, 6 | trailingComma: 'es5', 7 | }; 8 | -------------------------------------------------------------------------------- /example/.ruby-version: -------------------------------------------------------------------------------- 1 | 2.7.5 2 | -------------------------------------------------------------------------------- /example/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /example/android/app/_BUCK: -------------------------------------------------------------------------------- 1 | # To learn about Buck see [Docs](https://buckbuild.com/). 2 | # To run your application with Buck: 3 | # - install Buck 4 | # - `npm start` - to start the packager 5 | # - `cd android` 6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` 7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck 8 | # - `buck install -r android/app` - compile, install and run application 9 | # 10 | 11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets") 12 | 13 | lib_deps = [] 14 | 15 | create_aar_targets(glob(["libs/*.aar"])) 16 | 17 | create_jar_targets(glob(["libs/*.jar"])) 18 | 19 | android_library( 20 | name = "all-libs", 21 | exported_deps = lib_deps, 22 | ) 23 | 24 | android_library( 25 | name = "app-code", 26 | srcs = glob([ 27 | "src/main/java/**/*.java", 28 | ]), 29 | deps = [ 30 | ":all-libs", 31 | ":build_config", 32 | ":res", 33 | ], 34 | ) 35 | 36 | android_build_config( 37 | name = "build_config", 38 | package = "com.rn_example", 39 | ) 40 | 41 | android_resource( 42 | name = "res", 43 | package = "com.rn_example", 44 | res = "src/main/res", 45 | ) 46 | 47 | android_binary( 48 | name = "app", 49 | keystore = "//android/keystores:debug", 50 | manifest = "src/main/AndroidManifest.xml", 51 | package_type = "debug", 52 | deps = [ 53 | ":app-code", 54 | ], 55 | ) 56 | -------------------------------------------------------------------------------- /example/android/app/build_defs.bzl: -------------------------------------------------------------------------------- 1 | """Helper definitions to glob .aar and .jar targets""" 2 | 3 | def create_aar_targets(aarfiles): 4 | for aarfile in aarfiles: 5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")] 6 | lib_deps.append(":" + name) 7 | android_prebuilt_aar( 8 | name = name, 9 | aar = aarfile, 10 | ) 11 | 12 | def create_jar_targets(jarfiles): 13 | for jarfile in jarfiles: 14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")] 15 | lib_deps.append(":" + name) 16 | prebuilt_jar( 17 | name = name, 18 | binary_jar = jarfile, 19 | ) 20 | -------------------------------------------------------------------------------- /example/android/app/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/debug.keystore -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /example/android/app/src/debug/java/com/rn_example/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.rn_example; 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 | -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 13 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/rn_example/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.rn_example; 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 "rn_example"; 16 | } 17 | 18 | /** 19 | * Returns the instance of the {@link ReactActivityDelegate}. There the Button is created and 20 | * you can specify the renderer you wish to use - the new renderer (Fabric) or the old renderer 21 | * (Paper). 22 | */ 23 | @Override 24 | protected ReactActivityDelegate createReactActivityDelegate() { 25 | return new MainActivityDelegate(this, getMainComponentName()); 26 | } 27 | 28 | public static class MainActivityDelegate extends ReactActivityDelegate { 29 | public MainActivityDelegate(ReactActivity activity, String mainComponentName) { 30 | super(activity, mainComponentName); 31 | } 32 | 33 | @Override 34 | protected ReactRootView createRootView() { 35 | ReactRootView reactRootView = new ReactRootView(getContext()); 36 | // If you opted-in for the New Architecture, we enable the Fabric Renderer. 37 | reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED); 38 | return reactRootView; 39 | } 40 | 41 | @Override 42 | protected boolean isConcurrentRootEnabled() { 43 | // If you opted-in for the New Architecture, we enable Concurrent Root (i.e. React 18). 44 | // More on this on https://reactjs.org/blog/2022/03/29/react-v18.html 45 | return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/rn_example/MainApplication.java: -------------------------------------------------------------------------------- 1 | package com.rn_example; 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.rn_example.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.rn_example.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/main/java/com/rn_example/newarchitecture/MainApplicationReactNativeHost.java: -------------------------------------------------------------------------------- 1 | package com.rn_example.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.FabricJSIModuleProvider; 20 | import com.facebook.react.fabric.ReactNativeConfig; 21 | import com.facebook.react.uimanager.ViewManagerRegistry; 22 | import com.rn_example.BuildConfig; 23 | import com.rn_example.newarchitecture.components.MainComponentsRegistry; 24 | import com.rn_example.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 | ReactNativeConfig.DEFAULT_CONFIG, 109 | viewManagerRegistry); 110 | } 111 | }); 112 | return specs; 113 | } 114 | }; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/rn_example/newarchitecture/components/MainComponentsRegistry.java: -------------------------------------------------------------------------------- 1 | package com.rn_example.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/rn_example/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java: -------------------------------------------------------------------------------- 1 | package com.rn_example.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("rn_example_appmodules"); 45 | sIsSoLibraryLoaded = true; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.13) 2 | 3 | # Define the library name here. 4 | project(rn_example_appmodules) 5 | 6 | # This file includes all the necessary to let you build your application with the New Architecture. 7 | include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake) 8 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/MainApplicationModuleProvider.cpp: -------------------------------------------------------------------------------- 1 | #include "MainApplicationModuleProvider.h" 2 | 3 | #include 4 | #include 5 | 6 | namespace facebook { 7 | namespace react { 8 | 9 | std::shared_ptr MainApplicationModuleProvider( 10 | const std::string &moduleName, 11 | const JavaTurboModule::InitParams ¶ms) { 12 | // Here you can provide your own module provider for TurboModules coming from 13 | // either your application or from external libraries. The approach to follow 14 | // is similar to the following (for a library called `samplelibrary`: 15 | // 16 | // auto module = samplelibrary_ModuleProvider(moduleName, params); 17 | // if (module != nullptr) { 18 | // return module; 19 | // } 20 | // return rncore_ModuleProvider(moduleName, params); 21 | 22 | // Module providers autolinked by RN CLI 23 | auto rncli_module = rncli_ModuleProvider(moduleName, params); 24 | if (rncli_module != nullptr) { 25 | return rncli_module; 26 | } 27 | 28 | return rncore_ModuleProvider(moduleName, params); 29 | } 30 | 31 | } // namespace react 32 | } // namespace facebook 33 | -------------------------------------------------------------------------------- /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/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 | const 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/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/rn_example/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(const std::string &name); 35 | }; 36 | 37 | } // namespace react 38 | } // namespace facebook 39 | -------------------------------------------------------------------------------- /example/android/app/src/main/jni/MainComponentsRegistry.cpp: -------------------------------------------------------------------------------- 1 | #include "MainComponentsRegistry.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | namespace facebook { 10 | namespace react { 11 | 12 | MainComponentsRegistry::MainComponentsRegistry(ComponentFactory *delegate) {} 13 | 14 | std::shared_ptr 15 | MainComponentsRegistry::sharedProviderRegistry() { 16 | auto providerRegistry = CoreComponentsRegistry::sharedProviderRegistry(); 17 | 18 | // Autolinked providers registered by RN CLI 19 | rncli_registerProviders(providerRegistry); 20 | 21 | // Custom Fabric Components go here. You can register custom 22 | // components coming from your App or from 3rd party libraries here. 23 | // 24 | // providerRegistry->add(concreteComponentDescriptorProvider< 25 | // AocViewerComponentDescriptor>()); 26 | return providerRegistry; 27 | } 28 | 29 | jni::local_ref 30 | MainComponentsRegistry::initHybrid( 31 | jni::alias_ref, 32 | ComponentFactory *delegate) { 33 | auto instance = makeCxxInstance(delegate); 34 | 35 | auto buildRegistryFunction = 36 | [](EventDispatcher::Weak const &eventDispatcher, 37 | ContextContainer::Shared const &contextContainer) 38 | -> ComponentDescriptorRegistry::Shared { 39 | auto registry = MainComponentsRegistry::sharedProviderRegistry() 40 | ->createComponentDescriptorRegistry( 41 | {eventDispatcher, contextContainer}); 42 | 43 | auto mutableRegistry = 44 | std::const_pointer_cast(registry); 45 | 46 | mutableRegistry->setFallbackComponentDescriptor( 47 | std::make_shared( 48 | ComponentDescriptorParameters{ 49 | eventDispatcher, contextContainer, nullptr})); 50 | 51 | return registry; 52 | }; 53 | 54 | delegate->buildRegistryFunction = buildRegistryFunction; 55 | return instance; 56 | } 57 | 58 | void MainComponentsRegistry::registerNatives() { 59 | registerHybrid({ 60 | makeNativeMethod("initHybrid", MainComponentsRegistry::initHybrid), 61 | }); 62 | } 63 | 64 | } // namespace react 65 | } // namespace facebook 66 | -------------------------------------------------------------------------------- /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/rn_example/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 | -------------------------------------------------------------------------------- /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/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/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | rn_example 3 | 4 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /example/android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext { 5 | buildToolsVersion = "31.0.0" 6 | minSdkVersion = 21 7 | compileSdkVersion = 31 8 | targetSdkVersion = 31 9 | 10 | if (System.properties['os.arch'] == "aarch64") { 11 | // For M1 Users we need to use the NDK 24 which added support for aarch64 12 | ndkVersion = "24.0.8215888" 13 | } else { 14 | // Otherwise we default to the side-by-side NDK version from AGP. 15 | ndkVersion = "21.4.7075529" 16 | } 17 | } 18 | repositories { 19 | google() 20 | mavenCentral() 21 | } 22 | dependencies { 23 | classpath("com.android.tools.build:gradle:7.2.1") 24 | classpath("com.facebook.react:react-native-gradle-plugin") 25 | classpath("de.undercouch:gradle-download-task:5.0.1") 26 | // NOTE: Do not place your application dependencies here; they belong 27 | // in the individual module build.gradle files 28 | } 29 | } 30 | 31 | allprojects { 32 | repositories { 33 | maven { 34 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 35 | url("$rootDir/../node_modules/react-native/android") 36 | } 37 | maven { 38 | // Android JSC is installed from npm 39 | url("$rootDir/../node_modules/jsc-android/dist") 40 | } 41 | mavenCentral { 42 | // We don't want to fetch react-native from Maven Central as there are 43 | // older versions over there. 44 | content { 45 | excludeGroup "com.facebook.react" 46 | } 47 | } 48 | google() 49 | maven { url 'https://www.jitpack.io' } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /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 41 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimformSolutionsPvtLtd/react-native-graph-kit/2e0b6cc6a63ca3d25836b8b9e3ed0cd9fc8c134e/example/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /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.5.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /example/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original 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 POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /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/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'rn_example' 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 | include(":ReactAndroid:hermes-engine") 10 | project(":ReactAndroid:hermes-engine").projectDir = file('../node_modules/react-native/ReactAndroid/hermes-engine') 11 | } 12 | -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rn_example", 3 | "displayName": "rn_example" 4 | } -------------------------------------------------------------------------------- /example/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import { AppRegistry } from 'react-native'; 6 | 7 | import { name as appName } from './app.json'; 8 | import App from './src/App'; 9 | 10 | AppRegistry.registerComponent(appName, () => App); 11 | -------------------------------------------------------------------------------- /example/ios/.xcode.env: -------------------------------------------------------------------------------- 1 | # This `.xcode.env` file is versioned and is used to source the environment 2 | # used when running script phases inside Xcode. 3 | # To customize your local environment, you can create an `.xcode.env.local` 4 | # file that is not versioned. 5 | 6 | # NODE_BINARY variable contains the PATH to the node executable. 7 | # 8 | # Customize the NODE_BINARY variable here. 9 | # For example, to use nvm with brew, add the following line 10 | # . "$(brew --prefix nvm)/nvm.sh" --no-use 11 | export NODE_BINARY=$(command -v node) 12 | -------------------------------------------------------------------------------- /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, '12.4' 5 | install! 'cocoapods', :deterministic_uuids => false 6 | 7 | target 'rn_example' do 8 | config = use_native_modules! 9 | 10 | # Flags change depending on the env values. 11 | flags = get_default_flags() 12 | 13 | use_react_native!( 14 | :path => config[:reactNativePath], 15 | # Hermes is now enabled by default. Disable by setting this flag to false. 16 | # Upcoming versions of React Native may rely on get_default_flags(), but 17 | # we make it explicit here to aid in the React Native upgrade process. 18 | :hermes_enabled => false, 19 | # :fabric_enabled => flags[:fabric_enabled], 20 | # Enables Flipper. 21 | # 22 | # Note that if you have use_frameworks! enabled, Flipper will not work and 23 | # you should disable the next line. 24 | # :flipper_configuration => FlipperConfiguration.enabled, 25 | # An absolute path to your application root. 26 | :app_path => "#{Pod::Config.instance.installation_root}/.." 27 | ) 28 | 29 | target 'rn_exampleTests' do 30 | inherit! :complete 31 | # Pods for testing 32 | end 33 | 34 | post_install do |installer| 35 | react_native_post_install( 36 | installer, 37 | # Set `mac_catalyst_enabled` to `true` in order to apply patches 38 | # necessary for Mac Catalyst builds 39 | :mac_catalyst_enabled => false 40 | ) 41 | __apply_Xcode_12_5_M1_post_install_workaround(installer) 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /example/ios/rn_example.xcodeproj/xcshareddata/xcschemes/rn_example.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /example/ios/rn_example.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /example/ios/rn_example.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/rn_example/AppDelegate.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | @interface AppDelegate : UIResponder 5 | 6 | @property (nonatomic, strong) UIWindow *window; 7 | 8 | @end 9 | -------------------------------------------------------------------------------- /example/ios/rn_example/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 | static NSString *const kRNConcurrentRoot = @"concurrentRoot"; 20 | 21 | @interface AppDelegate () { 22 | RCTTurboModuleManager *_turboModuleManager; 23 | RCTSurfacePresenterBridgeAdapter *_bridgeAdapter; 24 | std::shared_ptr _reactNativeConfig; 25 | facebook::react::ContextContainer::Shared _contextContainer; 26 | } 27 | @end 28 | #endif 29 | 30 | @implementation AppDelegate 31 | 32 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 33 | { 34 | RCTAppSetupPrepareApp(application); 35 | 36 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; 37 | 38 | #if RCT_NEW_ARCH_ENABLED 39 | _contextContainer = std::make_shared(); 40 | _reactNativeConfig = std::make_shared(); 41 | _contextContainer->insert("ReactNativeConfig", _reactNativeConfig); 42 | _bridgeAdapter = [[RCTSurfacePresenterBridgeAdapter alloc] initWithBridge:bridge contextContainer:_contextContainer]; 43 | bridge.surfacePresenter = _bridgeAdapter.surfacePresenter; 44 | #endif 45 | 46 | NSDictionary *initProps = [self prepareInitialProps]; 47 | UIView *rootView = RCTAppSetupDefaultRootView(bridge, @"rn_example", initProps); 48 | 49 | if (@available(iOS 13.0, *)) { 50 | rootView.backgroundColor = [UIColor systemBackgroundColor]; 51 | } else { 52 | rootView.backgroundColor = [UIColor whiteColor]; 53 | } 54 | 55 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 56 | UIViewController *rootViewController = [UIViewController new]; 57 | rootViewController.view = rootView; 58 | self.window.rootViewController = rootViewController; 59 | [self.window makeKeyAndVisible]; 60 | return YES; 61 | } 62 | 63 | /// This method controls whether the `concurrentRoot`feature of React18 is turned on or off. 64 | /// 65 | /// @see: https://reactjs.org/blog/2022/03/29/react-v18.html 66 | /// @note: This requires to be rendering on Fabric (i.e. on the New Architecture). 67 | /// @return: `true` if the `concurrentRoot` feture is enabled. Otherwise, it returns `false`. 68 | - (BOOL)concurrentRootEnabled 69 | { 70 | // Switch this bool to turn on and off the concurrent root 71 | return true; 72 | } 73 | 74 | - (NSDictionary *)prepareInitialProps 75 | { 76 | NSMutableDictionary *initProps = [NSMutableDictionary new]; 77 | 78 | #ifdef RCT_NEW_ARCH_ENABLED 79 | initProps[kRNConcurrentRoot] = @([self concurrentRootEnabled]); 80 | #endif 81 | 82 | return initProps; 83 | } 84 | 85 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge 86 | { 87 | #if DEBUG 88 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"]; 89 | #else 90 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; 91 | #endif 92 | } 93 | 94 | #if RCT_NEW_ARCH_ENABLED 95 | 96 | #pragma mark - RCTCxxBridgeDelegate 97 | 98 | - (std::unique_ptr)jsExecutorFactoryForBridge:(RCTBridge *)bridge 99 | { 100 | _turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridge:bridge 101 | delegate:self 102 | jsInvoker:bridge.jsCallInvoker]; 103 | return RCTAppSetupDefaultJsExecutorFactory(bridge, _turboModuleManager); 104 | } 105 | 106 | #pragma mark RCTTurboModuleManagerDelegate 107 | 108 | - (Class)getModuleClassFromName:(const char *)name 109 | { 110 | return RCTCoreModulesClassProvider(name); 111 | } 112 | 113 | - (std::shared_ptr)getTurboModule:(const std::string &)name 114 | jsInvoker:(std::shared_ptr)jsInvoker 115 | { 116 | return nullptr; 117 | } 118 | 119 | - (std::shared_ptr)getTurboModule:(const std::string &)name 120 | initParams: 121 | (const facebook::react::ObjCTurboModule::InitParams &)params 122 | { 123 | return nullptr; 124 | } 125 | 126 | - (id)getModuleInstanceFromClass:(Class)moduleClass 127 | { 128 | return RCTAppSetupDefaultModuleFromClass(moduleClass); 129 | } 130 | 131 | #endif 132 | 133 | @end 134 | -------------------------------------------------------------------------------- /example/ios/rn_example/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/rn_example/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /example/ios/rn_example/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | rn_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/ios/rn_example/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 | -------------------------------------------------------------------------------- /example/ios/rn_example/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/rn_exampleTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/ios/rn_exampleTests/rn_exampleTests.m: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | #import 5 | #import 6 | 7 | #define TIMEOUT_SECONDS 600 8 | #define TEXT_TO_LOOK_FOR @"Welcome to React" 9 | 10 | @interface rn_exampleTests : XCTestCase 11 | 12 | @end 13 | 14 | @implementation rn_exampleTests 15 | 16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test 17 | { 18 | if (test(view)) { 19 | return YES; 20 | } 21 | for (UIView *subview in [view subviews]) { 22 | if ([self findSubviewInView:subview matching:test]) { 23 | return YES; 24 | } 25 | } 26 | return NO; 27 | } 28 | 29 | - (void)testRendersWelcomeScreen 30 | { 31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController]; 32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 33 | BOOL foundElement = NO; 34 | 35 | __block NSString *redboxError = nil; 36 | #ifdef DEBUG 37 | RCTSetLogFunction( 38 | ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 39 | if (level >= RCTLogLevelError) { 40 | redboxError = message; 41 | } 42 | }); 43 | #endif 44 | 45 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 46 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 47 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 48 | 49 | foundElement = [self findSubviewInView:vc.view 50 | matching:^BOOL(UIView *view) { 51 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 52 | return YES; 53 | } 54 | return NO; 55 | }]; 56 | } 57 | 58 | #ifdef DEBUG 59 | RCTSetLogFunction(RCTDefaultLogFunction); 60 | #endif 61 | 62 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 63 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 64 | } 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /example/metro.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Metro configuration for React Native 3 | * https://github.com/facebook/react-native 4 | * 5 | * @format 6 | */ 7 | const path = require('path'); 8 | const rootPackage = require('../package.json'); 9 | const blacklist = require('metro-config/src/defaults/exclusionList'); 10 | const rootModules = Object.keys({ 11 | ...rootPackage.peerDependencies, 12 | }); 13 | const moduleRoot = path.resolve(__dirname, '..'); 14 | /** 15 | * Only load one version for peerDependencies and alias them to the versions in example's node_modules" 16 | */ 17 | module.exports = { 18 | watchFolders: [moduleRoot], 19 | resolver: { 20 | blacklistRE: blacklist([ 21 | ...rootModules.map( 22 | m => 23 | new RegExp( 24 | `^${escape(path.join(moduleRoot, 'node_modules', m))}\\/.*$` 25 | ) 26 | ), 27 | /^((?!example).)+[\/\\]node_modules[/\\]react[/\\].*/, 28 | /^((?!example).)+[\/\\]node_modules[/\\]react-native[/\\].*/, 29 | ]), 30 | extraNodeModules: { 31 | ...rootModules.reduce((acc, name) => { 32 | acc[name] = path.join(__dirname, 'node_modules', name); 33 | return acc; 34 | }, {}), 35 | }, 36 | }, 37 | transformer: { 38 | getTransformOptions: async () => ({ 39 | transform: { 40 | experimentalImportSupport: false, 41 | inlineRequires: true, 42 | }, 43 | }), 44 | }, 45 | }; 46 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rn_example", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "android": "react-native run-android", 7 | "ios": "react-native run-ios", 8 | "start": "react-native start", 9 | "test": "jest", 10 | "lint": "eslint . --ext .js,.jsx,.ts,.tsx" 11 | }, 12 | "dependencies": { 13 | "@shopify/react-native-skia": "^0.1.228", 14 | "react": "18.1.0", 15 | "react-native": "0.70.0", 16 | "react-native-graph-kit": "../" 17 | }, 18 | "devDependencies": { 19 | "@babel/core": "^7.12.9", 20 | "@babel/runtime": "^7.12.5", 21 | "@react-native-community/eslint-config": "^2.0.0", 22 | "@tsconfig/react-native": "^2.0.2", 23 | "@types/jest": "^26.0.23", 24 | "@types/react-native": "^0.69.6", 25 | "@types/react-test-renderer": "^18.0.0", 26 | "@typescript-eslint/eslint-plugin": "^5.36.2", 27 | "@typescript-eslint/parser": "^5.36.2", 28 | "babel-jest": "^26.6.3", 29 | "eslint": "^7.32.0", 30 | "jest": "^26.6.3", 31 | "metro-react-native-babel-preset": "^0.72.1", 32 | "react-test-renderer": "18.1.0", 33 | "typescript": "^4.8.2" 34 | }, 35 | "resolutions": { 36 | "@types/react": "*" 37 | }, 38 | "jest": { 39 | "preset": "react-native", 40 | "moduleFileExtensions": [ 41 | "ts", 42 | "tsx", 43 | "js", 44 | "jsx", 45 | "json", 46 | "node" 47 | ] 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { SafeAreaView, View } from 'react-native'; 3 | import { BarChart, LineChart } from 'react-native-graph-kit'; 4 | import { data } from './constants'; 5 | import { ApplicationStyles, Colors } from './theme'; 6 | 7 | const App = () => { 8 | return ( 9 | 10 | 11 | 20 | 21 | 22 | 28 | 29 | 30 | ); 31 | }; 32 | 33 | export default App; 34 | -------------------------------------------------------------------------------- /example/src/constants/StaticData.ts: -------------------------------------------------------------------------------- 1 | export const data = { 2 | xAxis: { 3 | labels: [ 4 | 'Alice', 5 | 'Bob', 6 | 'Charlie', 7 | 'Liam', 8 | 'Mia', 9 | 'Nora', 10 | 'Oliver', 11 | 'Penelope', 12 | 'Quinn', 13 | 'Ryan', 14 | 'Sophia', 15 | ], 16 | }, 17 | yAxis: { 18 | datasets: [220, 350, 400, 170, 317, 655, 320, 200, 400, 370, 270], 19 | }, 20 | }; 21 | -------------------------------------------------------------------------------- /example/src/constants/Strings.ts: -------------------------------------------------------------------------------- 1 | export const Strings = { 2 | xAxisLegend: 'Days Count', 3 | yAxisLegend: 'Stock Price', 4 | }; 5 | -------------------------------------------------------------------------------- /example/src/constants/index.ts: -------------------------------------------------------------------------------- 1 | export * from './Strings'; 2 | export * from './StaticData'; 3 | -------------------------------------------------------------------------------- /example/src/theme/ApplicationStyles.ts: -------------------------------------------------------------------------------- 1 | import { StyleSheet } from 'react-native'; 2 | import { horizontalScale, moderateScale, verticalScale } from './Metrics'; 3 | import Colors from './Colors'; 4 | 5 | /** 6 | * A StyleSheet object that contains all of the application's styles. 7 | * @param {ThemeMode} theme - The theme of the application. 8 | * @returns {StyleSheet} - A StyleSheet object containing all of the application's styles. 9 | */ 10 | const applicationStyles = StyleSheet.create({ 11 | screen: { 12 | flex: 1, 13 | }, 14 | chartContainer: { 15 | flex: 1, 16 | borderRadius: moderateScale(10), 17 | borderWidth: 1, 18 | borderColor: Colors.grey, 19 | padding: moderateScale(10), 20 | margin: moderateScale(10), 21 | shadowColor: Colors.grey, 22 | shadowOpacity: 1, 23 | backgroundColor: Colors.white, 24 | shadowOffset: { 25 | height: verticalScale(6), 26 | width: horizontalScale(5), 27 | }, 28 | }, 29 | }); 30 | 31 | export default applicationStyles; 32 | -------------------------------------------------------------------------------- /example/src/theme/Colors.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | white: '#ffffff', 3 | black: '#000000', 4 | blue: '#05259b', 5 | cherryRed: '#DE5E69', 6 | grey: '#D3D3D3', 7 | pink: '#FFC0CB', 8 | violet: '#EE82EE', 9 | orange: '#FFA500', 10 | lightViolet: '#f5e2ff', 11 | }; 12 | -------------------------------------------------------------------------------- /example/src/theme/Metrics.tsx: -------------------------------------------------------------------------------- 1 | import { Dimensions, Platform, type ScaledSize } from 'react-native'; 2 | 3 | /** 4 | * Get the width and height of the device screen. 5 | * @returns {ScaledSize} - the width and height of the device screen. 6 | */ 7 | let { width, height }: ScaledSize = Dimensions.get('window'); 8 | 9 | if (width > height) { 10 | [width, height] = [height, width]; 11 | } 12 | 13 | //Guideline sizes are based on standard ~5" screen mobile device 14 | const guidelineBaseWidth: number = 375; 15 | 16 | const guidelineBaseHeight: number = 812; 17 | 18 | /** 19 | * Converts provided width to based on provided guideline size width. 20 | * @param {number} size The screen's width that UI element should cover 21 | * @return {number} The calculated scale depending on current device's screen width. 22 | */ 23 | const horizontalScale = (size: number): number => 24 | (width / guidelineBaseWidth) * size; 25 | 26 | /** 27 | * Converts provided height to based on provided guideline size height. 28 | * @param {number} size The screen's height that UI element should cover 29 | * @return {number} The calculated vertical scale depending on current device's screen height. 30 | */ 31 | const verticalScale = (size: number): number => 32 | (height / guidelineBaseHeight) * size; 33 | 34 | /** 35 | * Converts provided size to based on provided guideline size width. 36 | * @param {number} size - The size of the font you want to scale 37 | * @param {number} [factor=0.5] - The amount of scaling to apply to font sizes. Defaults to 0.5. 38 | * @return {number} The calculated moderate scale depending on current device's screen width. 39 | */ 40 | const moderateScale = (size: number, factor = 0.5): number => 41 | size + (horizontalScale(size) - size) * factor; 42 | 43 | /** 44 | * A type that contains the global metrics for the current device. 45 | * @typedef {Object} GlobalMetricsType - A type that contains the global metrics for the current device. 46 | * @property {boolean} isAndroid - Whether the current device is an Android device. 47 | */ 48 | interface GlobalMetricsType { 49 | isAndroid: boolean; 50 | isIos: boolean; 51 | isPad: boolean; 52 | isTV: boolean; 53 | isWeb: boolean; 54 | } 55 | 56 | /** 57 | * A type that contains the global metrics for the app. 58 | * @type {GlobalMetricsType} 59 | */ 60 | const globalMetrics: GlobalMetricsType = { 61 | isAndroid: Platform.OS === 'android', 62 | isIos: Platform.OS === 'ios', 63 | isPad: Platform.OS === 'ios' && Platform.isPad, 64 | isTV: Platform.isTV, 65 | isWeb: Platform.OS === 'web', 66 | }; 67 | 68 | export { 69 | globalMetrics, 70 | horizontalScale, 71 | verticalScale, 72 | moderateScale, 73 | width, 74 | height, 75 | }; 76 | -------------------------------------------------------------------------------- /example/src/theme/index.ts: -------------------------------------------------------------------------------- 1 | export { default as ApplicationStyles } from './ApplicationStyles'; 2 | export { default as Colors } from './Colors'; 3 | export * from './Metrics'; 4 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "esModuleInterop": true, 5 | "jsx": "react-native", 6 | "lib": ["ESNext"], 7 | "module": "CommonJS", 8 | "noEmit": true, 9 | "paths": { 10 | "react-native-graph-kit": ["../src"] 11 | }, 12 | "declaration": true, 13 | "allowUnreachableCode": false, 14 | "allowUnusedLabels": false, 15 | "importsNotUsedAsValues": "error", 16 | "forceConsistentCasingInFileNames": true, 17 | "moduleResolution": "Node", 18 | "noFallthroughCasesInSwitch": true, 19 | "noImplicitReturns": true, 20 | "noImplicitUseStrict": false, 21 | "noStrictGenericChecks": false, 22 | "noUnusedLocals": true, 23 | "noUnusedParameters": true, 24 | "resolveJsonModule": true, 25 | "noEmitOnError": true, 26 | "skipLibCheck": true, 27 | "sourceMap": true, 28 | "strict": true, 29 | "target": "ES2018" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-graph-kit", 3 | "version": "1.0.1", 4 | "description": "Personalized graphs featuring customizable options for React Native app", 5 | "main": "lib/index", 6 | "types": "lib/index.d.ts", 7 | "author": "Simform Solutions", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/SimformSolutionsPvtLtd/react-native-graph-kit" 11 | }, 12 | "homepage": "https://github.com/SimformSolutionsPvtLtd/react-native-graph-kit#readme", 13 | "keywords": [ 14 | "react", 15 | "react-native", 16 | "typescript", 17 | "rn", 18 | "chart", 19 | "graph", 20 | "visualization", 21 | "line-chart", 22 | "bar-chart", 23 | "react-native-skia", 24 | "data-visualization", 25 | "open-source", 26 | "javascript", 27 | "skia", 28 | "react-native-library" 29 | ], 30 | "license": "MIT", 31 | "files": [ 32 | "/lib" 33 | ], 34 | "scripts": { 35 | "prepare": "husky install && yarn build", 36 | "clean": "rm -rf node_modules", 37 | "build": "rm -rf lib && tsc -p . ", 38 | "lint": "eslint . --ext .js,.jsx,.ts,.tsx", 39 | "lint:fix": "eslint 'src/**/*.{js,jsx,ts,tsx}' -c .eslintrc --fix ", 40 | "build:local": "yarn build && yarn pack", 41 | "test": "jest", 42 | "example": "yarn --cwd example" 43 | }, 44 | "peerDependencies": { 45 | "@shopify/react-native-skia": "0.1.228", 46 | "d3-scale": "4.0.2", 47 | "react": "*", 48 | "react-native": "*" 49 | }, 50 | "devDependencies": { 51 | "@babel/core": "^7.12.9", 52 | "@babel/runtime": "^7.12.5", 53 | "@commitlint/cli": "^16.1.0", 54 | "@commitlint/config-conventional": "^16.0.0", 55 | "@react-native-community/eslint-config": "^3.0.1", 56 | "@testing-library/react-native": "^9.0.0", 57 | "@tsconfig/react-native": "^2.0.2", 58 | "@types/d3-scale": "^4.0.8", 59 | "@types/jest": "^27.4.0", 60 | "@types/react-native": "^0.69.5", 61 | "@types/react-test-renderer": "^18.0.0", 62 | "@typescript-eslint/eslint-plugin": "^5.29.0", 63 | "@typescript-eslint/parser": "^5.29.0", 64 | "babel-jest": "^27.4.6", 65 | "eslint": "^7.32.0", 66 | "eslint-plugin-simple-import-sort": "^7.0.0", 67 | "husky": "^8.0.1", 68 | "jest": "^27.4.7", 69 | "lint-staged": "^11.1.2", 70 | "metro-react-native-babel-preset": "^0.70.3", 71 | "prettier": "^2.7.1", 72 | "react": "18.1.0", 73 | "react-native": "0.70.0", 74 | "react-test-renderer": "18.0.0", 75 | "typescript": "4.7.4" 76 | }, 77 | "husky": { 78 | "hooks": { 79 | "pre-commit": "lint-staged", 80 | "pre-push": "yarn build && yarn test" 81 | } 82 | }, 83 | "lint-staged": { 84 | "src/**/*.{js,ts,tsx}": [ 85 | "eslint" 86 | ] 87 | }, 88 | "resolutions": { 89 | "@types/react": "*" 90 | }, 91 | "jest": { 92 | "preset": "react-native", 93 | "moduleFileExtensions": [ 94 | "ts", 95 | "tsx", 96 | "js", 97 | "jsx", 98 | "json", 99 | "node" 100 | ], 101 | "setupFilesAfterEnv": [], 102 | "modulePathIgnorePatterns": [] 103 | }, 104 | "eslintIgnore": [ 105 | "node_modules/", 106 | "lib/" 107 | ], 108 | "commitlint": { 109 | "extends": [ 110 | "@commitlint/config-conventional" 111 | ] 112 | }, 113 | "dependencies": { 114 | "@shopify/react-native-skia": "0.1.228", 115 | "d3-scale": "4.0.2" 116 | } 117 | } -------------------------------------------------------------------------------- /src/components/bar-chart/BarChart.tsx: -------------------------------------------------------------------------------- 1 | import { Canvas, Path } from '@shopify/react-native-skia'; 2 | import React from 'react'; 3 | import { ScrollView, Text as RNText, View } from 'react-native'; 4 | import { Colors } from '../../theme'; 5 | import { Tooltip } from '../tooltip'; 6 | import { styles } from './BarChartStyles'; 7 | import type { BarChartProps } from './BarChartTypes'; 8 | import { RenderHorizontalGridLines, XAxisLabels, YAxisLabels } from './components'; 9 | import useBarChart from './useBarChart'; 10 | 11 | /** 12 | * BarChart Component for displaying bar charts with customizable styling and features. 13 | * 14 | * @param {object} props - The properties of the BarChart Component. 15 | * @param {Array} props.chartData - Data used to render the bar chart. 16 | * @param {number} [props.barGap=50] - Gap between bars. 17 | * @param {number} [props.chartHeight=500] - Height of the chart. 18 | * @param {number} [props.barWidth=20] - Width of each bar. 19 | * @param {string} [props.barColor=Colors.cherryRed] - Color of the bars. 20 | * @param {number} [props.barRadius=0] - Border radius of the bars. 21 | * @param {number} [props.labelSize=17] - Font size of labels. 22 | * @param {string} [props.labelColor=Colors.black] - Color of labels. 23 | * @param {string} [props.labelFontFamily] - Font family for labels. 24 | * @param {boolean} [props.showLines=true] - Whether to display grid lines. 25 | * @param {number} [props.lineHeight=2] - Height of grid lines. 26 | * @param {boolean} [props.verticalLabel=false] - Whether to display vertical labels. 27 | * @param {string} [props.horizontalGridLineColor=Colors.black] - Color of horizontal grid lines. 28 | * @param {number} [props.yAxisMax] - Maximum value for the y-axis. 29 | * @param {number} [props.yAxisMin] - Minimum value for the y-axis. 30 | * @param {number} [props.initialDistance=0] - Initial distance for the chart. 31 | * @param {string} [props.chartBackGroundColor=Colors.white] - Background color of the chart. 32 | * @param {string} [props.yAxisLegend] - Label for the y-axis. 33 | * @param {string} [props.xAxisLegend] - Label for the x-axis. 34 | * @param {number} [props.legendSize=15] - Font size of the legend. 35 | * @param {number} [props.toolTipLabelFontSize] - Font size of the tooltip labels. 36 | * @param {string} [props.toolTipColor] - Background color of the tooltip. 37 | * @param {string} [props.toolTipDataColor] - Color of the tooltip data. 38 | * @param {number} [props.toolTipHorizontalPadding] - Horizontal padding of the tooltip. 39 | * @param {number} [props.toolTipFadeOutDuration] - Tooltip fade-out duration. 40 | * @param {boolean} [props.displayTooltip=false] - Whether to display tooltips. 41 | * @param {boolean} [props.showAnimation=true] - Whether to show animation. 42 | * @param {object} [props.xLegendStyles] - Styles for x-axis legend. 43 | * @param {object} [props.yLegendStyles] - Styles for y-axis legend. 44 | * @returns {React.ReactElement} - The rendered BarChart component. 45 | */ 46 | const BarChart = ({ 47 | chartData, 48 | barGap = 50, 49 | chartHeight = 500, 50 | barWidth = 20, 51 | barColor = Colors.cherryRed, 52 | barRadius = 0, 53 | labelSize = 17, 54 | labelColor = Colors.black, 55 | labelFontFamily, 56 | showLines = true, 57 | lineHeight = 2, 58 | verticalLabel = false, 59 | horizontalGridLineColor = Colors.black, 60 | yAxisMax, 61 | yAxisMin, 62 | initialDistance = 0, 63 | chartBackGroundColor = Colors.white, 64 | yAxisLegend = '', 65 | xAxisLegend = '', 66 | legendSize = 15, 67 | toolTipLabelFontSize, 68 | toolTipColor, 69 | toolTipDataColor, 70 | toolTipHorizontalPadding, 71 | toolTipFadeOutDuration, 72 | displayTooltip = false, 73 | showAnimation = true, 74 | xLegendStyles = {}, 75 | yLegendStyles = {} 76 | }: BarChartProps): React.ReactElement => { 77 | const { 78 | font, 79 | xScale, 80 | path, 81 | canvasHeightWithHorizontalLabel, 82 | xAxisData, 83 | canvasHeight, 84 | CHART_BOTTOM_MARGIN, 85 | yScale, 86 | AXIS_POSITION_VALUE, 87 | yLabelMaxLength, 88 | barChartHeight, 89 | barLegendHeight, 90 | yLabelWidth, 91 | canvasWidth, 92 | barChartWidth, 93 | xLabelPaddingLeft, 94 | touchHandler, 95 | xForWindow, 96 | xCoordinateForDataPoint, 97 | yCoordinateForDataPoint, 98 | pointData, 99 | windowSize, 100 | setXForWindow, 101 | setWindowSize, 102 | xLabelMarginLeft, 103 | yAxisLegendStyles, 104 | xAxisLegendStyles, 105 | radiusPath 106 | } = useBarChart({ 107 | chartData, 108 | chartHeight, 109 | yAxisMax, 110 | yAxisMin, 111 | labelFontFamily, 112 | barRadius, 113 | labelSize, 114 | barWidth, 115 | barGap, 116 | initialDistance, 117 | yAxisLegend, 118 | legendSize, 119 | verticalLabel, 120 | showAnimation, 121 | xLegendStyles, 122 | yLegendStyles 123 | }); 124 | 125 | if (font === null) { 126 | return <>; 127 | } 128 | const style = styles({ 129 | barChartHeight, 130 | chartBackGroundColor, 131 | barLegendHeight, 132 | yLabelWidth, 133 | legendSize, 134 | canvasWidth, 135 | barChartWidth, 136 | xLabelPaddingLeft, 137 | xLabelMarginLeft 138 | }); 139 | 140 | return ( 141 | <> 142 | 145 | {yAxisLegend && ( 146 | 147 | 148 | {yAxisLegend} 149 | 150 | 151 | )} 152 | 153 | 154 | 155 | 165 | 166 | 167 | 175 | 179 | {showLines && ( 180 | 195 | )} 196 | 197 | 198 | 212 | {displayTooltip && ( 213 | 230 | )} 231 | 232 | 233 | 234 | 235 | 236 | {xAxisLegend && ( 237 | 238 | 242 | {xAxisLegend} 243 | 244 | 245 | )} 246 | 247 | 248 | ); 249 | }; 250 | 251 | export default BarChart; 252 | -------------------------------------------------------------------------------- /src/components/bar-chart/BarChartStyles.ts: -------------------------------------------------------------------------------- 1 | import { StyleSheet } from 'react-native'; 2 | import type { BarChartStylePropType } from './BarChartTypes'; 3 | 4 | export const styles = ({ 5 | barChartHeight, 6 | chartBackGroundColor, 7 | barLegendHeight, 8 | yLabelWidth, 9 | legendSize, 10 | canvasWidth, 11 | barChartWidth, 12 | xLabelMarginLeft 13 | }: BarChartStylePropType) => 14 | StyleSheet.create({ 15 | flexRow: { 16 | flexDirection: 'row' 17 | }, 18 | fullWidth: { 19 | width: '100%' 20 | }, 21 | container: { 22 | flex: 0.1, 23 | justifyContent: 'center', 24 | alignItems: 'center', 25 | overflow: 'hidden' 26 | }, 27 | alignCenter: { 28 | alignSelf: 'center' 29 | }, 30 | chartWrapper: { 31 | flex: 1, 32 | flexDirection: 'row' 33 | }, 34 | yLabelWrapper: { 35 | justifyContent: 'center', 36 | alignItems: 'center', 37 | transform: [{ rotate: '-90deg' }], 38 | width: yLabelWidth 39 | }, 40 | xAxisLabel: { 41 | paddingLeft: xLabelMarginLeft 42 | }, 43 | barChartWrapper: { 44 | height: barChartHeight 45 | }, 46 | yAxisLegendWrapper: { 47 | height: barLegendHeight 48 | }, 49 | yLegendTextStyle: { 50 | fontSize: legendSize 51 | }, 52 | canvasWidth: { 53 | width: canvasWidth 54 | }, 55 | chartCanvasContainer: { 56 | height: barChartHeight, 57 | width: barChartWidth 58 | }, 59 | chartBackGroundColor: { 60 | backgroundColor: chartBackGroundColor 61 | }, 62 | xLegendText: { 63 | fontSize: legendSize 64 | } 65 | }); 66 | -------------------------------------------------------------------------------- /src/components/bar-chart/BarChartTypes.ts: -------------------------------------------------------------------------------- 1 | import type { DataSource } from '@shopify/react-native-skia'; 2 | import type { TextStyle } from 'react-native'; 3 | 4 | type ChartDataType = { 5 | xAxis: { 6 | labels: string[]; 7 | }; 8 | yAxis: { 9 | datasets: number[]; 10 | }; 11 | }; 12 | 13 | type Enumerate = Acc['length'] extends N 14 | ? Acc[number] 15 | : Enumerate; 16 | 17 | export type Range = Exclude, Enumerate>; 18 | 19 | type BarChartProps = { 20 | chartData: ChartDataType; 21 | barGap?: Range<0, 999>; 22 | chartHeight?: Range<0, 999>; 23 | barWidth?: Range<0, 200>; 24 | barColor?: string; 25 | barRadius?: Range<0, 200>; 26 | labelSize?: Range<0, 50>; 27 | labelSelectedColor?: string; 28 | labelColor?: string; 29 | labelFontFamily?: DataSource; 30 | showLines?: boolean; 31 | lineHeight?: Range<0, 4>; 32 | verticalLabel?: boolean; 33 | horizontalGridLineColor?: string; 34 | yAxisMax?: number; 35 | chartBackGroundColor?: string; 36 | initialDistance?: Range<0, 150>; 37 | yAxisMin?: number; 38 | yAxisLegend?: string; 39 | xAxisLegend?: string; 40 | legendSize?: number; 41 | toolTipLabelFontSize?: number; 42 | toolTipColor?: string; 43 | toolTipDataColor?: string; 44 | toolTipHorizontalPadding?: number; 45 | toolTipFadeOutDuration?: number; 46 | displayTooltip?: boolean; 47 | showAnimation?: boolean; 48 | xLegendStyles?: TextStyle; 49 | yLegendStyles?: TextStyle; 50 | }; 51 | 52 | interface BarChartHookPropType { 53 | chartData: ChartDataType; 54 | chartHeight: Range<0, 999>; 55 | yAxisMax?: number; 56 | yAxisMin?: number; 57 | labelFontFamily?: DataSource; 58 | barRadius: number; 59 | labelSize: Range<0, 50>; 60 | barWidth: number; 61 | barGap: Range<0, 999>; 62 | initialDistance: Range<0, 150>; 63 | yAxisLegend: string; 64 | legendSize: number; 65 | verticalLabel: boolean; 66 | showAnimation?: boolean; 67 | yLegendStyles: TextStyle; 68 | xLegendStyles: TextStyle; 69 | } 70 | 71 | interface BarChartStylePropType { 72 | barChartHeight: number; 73 | chartBackGroundColor: string; 74 | barLegendHeight: number; 75 | yLabelWidth: number; 76 | legendSize: number; 77 | canvasWidth: number; 78 | barChartWidth: number; 79 | xLabelPaddingLeft: number; 80 | xLabelMarginLeft: number; 81 | } 82 | 83 | export { BarChartProps, ChartDataType, BarChartHookPropType, BarChartStylePropType }; 84 | -------------------------------------------------------------------------------- /src/components/bar-chart/components/index.ts: -------------------------------------------------------------------------------- 1 | export * from './xaxis-label'; 2 | export * from './yaxis-label'; 3 | export * from './yref-lines'; 4 | -------------------------------------------------------------------------------- /src/components/bar-chart/components/xaxis-label/XAxisLabels.tsx: -------------------------------------------------------------------------------- 1 | import { Text } from '@shopify/react-native-skia'; 2 | import React from 'react'; 3 | import type { XAxisLabelsPropType } from './XAxisLabelsTypes'; 4 | 5 | const XAxisLabels = ({ 6 | xAxisData, 7 | verticalLabel, 8 | font, 9 | xScale, 10 | yLabelMaxLength, 11 | barWidth, 12 | initialDistance, 13 | canvasHeight, 14 | labelColor, 15 | canvasHeightWithHorizontalLabel 16 | }: XAxisLabelsPropType) => { 17 | return ( 18 | <> 19 | {xAxisData?.map((dataPoint, index) => { 20 | const { height, width } = font?.measureText(dataPoint); 21 | const xScaleWidth = (xScale(dataPoint) as number) + barWidth / 2 + initialDistance; 22 | const xPoint = verticalLabel 23 | ? xScaleWidth + yLabelMaxLength - width + height / 3 24 | : xScaleWidth + yLabelMaxLength - width / 2; 25 | const yOrigin = verticalLabel ? canvasHeight : canvasHeightWithHorizontalLabel; 26 | const xOrigin = verticalLabel ? xScaleWidth + yLabelMaxLength + height / 3 : xScaleWidth; 27 | const rotationDeg = verticalLabel ? -((Math.PI / 180) * 90) : 0; 28 | 29 | return ( 30 | 43 | ); 44 | })} 45 | 46 | ); 47 | }; 48 | export default XAxisLabels; 49 | -------------------------------------------------------------------------------- /src/components/bar-chart/components/xaxis-label/XAxisLabelsTypes.ts: -------------------------------------------------------------------------------- 1 | import type { SkFont } from '@shopify/react-native-skia'; 2 | import type { ScalePoint } from 'd3-scale'; 3 | 4 | export interface XAxisLabelsPropType { 5 | xAxisData: string[]; 6 | verticalLabel: boolean; 7 | font: SkFont; 8 | yLabelMaxLength: number; 9 | barWidth: number; 10 | initialDistance: number; 11 | canvasHeight: number; 12 | labelColor: string; 13 | canvasHeightWithHorizontalLabel: number; 14 | xScale: ScalePoint; 15 | } 16 | -------------------------------------------------------------------------------- /src/components/bar-chart/components/xaxis-label/index.ts: -------------------------------------------------------------------------------- 1 | export { default as XAxisLabels } from './XAxisLabels'; 2 | -------------------------------------------------------------------------------- /src/components/bar-chart/components/yaxis-label/YAxisLabels.tsx: -------------------------------------------------------------------------------- 1 | import { Text } from '@shopify/react-native-skia'; 2 | import React from 'react'; 3 | import type { YAxisLabelsPropsType } from './YAxisLabelsPropsTypes'; 4 | 5 | const YAxisLabels = ({ 6 | yScale, 7 | font, 8 | canvasHeight, 9 | AXIS_POSITION_VALUE, 10 | labelColor, 11 | CHART_BOTTOM_MARGIN 12 | }: YAxisLabelsPropsType) => { 13 | return ( 14 | <> 15 | {yScale.ticks().map((tick: number, index: number) => { 16 | const yPoint = canvasHeight - 2 * CHART_BOTTOM_MARGIN - yScale(tick) + AXIS_POSITION_VALUE; 17 | return ( 18 | 26 | ); 27 | })} 28 | 29 | ); 30 | }; 31 | export default YAxisLabels; 32 | -------------------------------------------------------------------------------- /src/components/bar-chart/components/yaxis-label/YAxisLabelsPropsTypes.ts: -------------------------------------------------------------------------------- 1 | import type { SkFont } from '@shopify/react-native-skia'; 2 | import type { ScaleLinear } from 'd3-scale'; 3 | 4 | export interface YAxisLabelsPropsType { 5 | font: SkFont; 6 | canvasHeight: number; 7 | AXIS_POSITION_VALUE: number; 8 | labelColor: string; 9 | CHART_BOTTOM_MARGIN: number; 10 | yScale: ScaleLinear; 11 | } 12 | -------------------------------------------------------------------------------- /src/components/bar-chart/components/yaxis-label/index.ts: -------------------------------------------------------------------------------- 1 | export { default as YAxisLabels } from './YAxisLabels'; 2 | -------------------------------------------------------------------------------- /src/components/bar-chart/components/yref-lines/YRefLines.tsx: -------------------------------------------------------------------------------- 1 | import { Rect } from '@shopify/react-native-skia'; 2 | import React from 'react'; 3 | import type { YRefLinesProps } from './YRefLinesTypes'; 4 | 5 | const YRefLines = ({ 6 | xScale, 7 | xAxisData, 8 | barWidth, 9 | yScale, 10 | AXIS_POSITION_VALUE, 11 | lineHeight, 12 | canvasHeight, 13 | CHART_BOTTOM_MARGIN, 14 | horizontalGridLineColor, 15 | initialDistance, 16 | yLabelMaxLength 17 | }: YRefLinesProps) => { 18 | const startXPosition = xScale(xAxisData?.[0]); 19 | const endXPosition = xScale(xAxisData?.[xAxisData?.length - 1]); 20 | const startX: number = (startXPosition as number) + yLabelMaxLength + initialDistance; 21 | const endX: number = (endXPosition as number) + barWidth + initialDistance; 22 | 23 | return ( 24 | <> 25 | {yScale.ticks().map((tick: number, index: number) => { 26 | const yPoint = canvasHeight - 2 * CHART_BOTTOM_MARGIN - yScale(tick) + AXIS_POSITION_VALUE; 27 | return ( 28 | 36 | ); 37 | })} 38 | 39 | ); 40 | }; 41 | export default YRefLines; 42 | -------------------------------------------------------------------------------- /src/components/bar-chart/components/yref-lines/YRefLinesTypes.ts: -------------------------------------------------------------------------------- 1 | import type { ScaleLinear, ScalePoint } from 'd3-scale'; 2 | 3 | export interface YRefLinesProps { 4 | xAxisData: string[]; 5 | barWidth: number; 6 | AXIS_POSITION_VALUE: number; 7 | lineHeight: number; 8 | canvasHeight: number; 9 | CHART_BOTTOM_MARGIN: number; 10 | horizontalGridLineColor: string; 11 | initialDistance: number; 12 | yLabelMaxLength: number; 13 | yScale: ScaleLinear; 14 | xScale: ScalePoint; 15 | } 16 | -------------------------------------------------------------------------------- /src/components/bar-chart/components/yref-lines/index.ts: -------------------------------------------------------------------------------- 1 | export { default as RenderHorizontalGridLines } from './YRefLines'; 2 | -------------------------------------------------------------------------------- /src/components/bar-chart/index.ts: -------------------------------------------------------------------------------- 1 | export { default as BarChart } from './BarChart'; 2 | export * from './BarChartTypes'; 3 | export { default as useBarChart } from './useBarChart'; 4 | -------------------------------------------------------------------------------- /src/components/bar-chart/useBarChart.ts: -------------------------------------------------------------------------------- 1 | import { 2 | matchFont, 3 | runTiming, 4 | SkFont, 5 | Skia, 6 | useComputedValue, 7 | useFont, 8 | useTouchHandler, 9 | useValue 10 | } from '@shopify/react-native-skia'; 11 | import { scaleLinear, scalePoint, type NumberValue } from 'd3-scale'; 12 | import { useEffect } from 'react'; 13 | import { Easing } from 'react-native'; 14 | import { 15 | AXIS_POSITION_VALUE, 16 | BARGRAPH_TOOLTIP_HITSLOP, 17 | CHART_BOTTOM_MARGIN, 18 | INITIAL_SPACE 19 | } from '../../constants'; 20 | import { useDefaultFont } from '../../hooks'; 21 | import { chartWidth, Colors, horizontalScale, screenHeight } from '../../theme'; 22 | import { useTooltipUtils } from '../tooltip'; 23 | import type { BarChartHookPropType } from './BarChartTypes'; 24 | 25 | /** 26 | * Custom React hook for handling Bar Chart rendering and animation. 27 | * 28 | * This hook processes and calculates various properties necessary for rendering a Bar Chart, 29 | * including scaling, animation, and tooltip interactions. It utilizes D3 scales and Skia paths 30 | * for efficient rendering and customization. 31 | * 32 | * @param {BarChartHookPropType} props - The properties required for the Bar Chart hook. 33 | * @returns An object containing various properties and functions for rendering and interacting 34 | * with the Bar Chart, including font information, scales, paths, and animation states. 35 | */ 36 | export default function useBarChart({ 37 | chartData, 38 | chartHeight, 39 | yAxisMax, 40 | yAxisMin, 41 | labelFontFamily, 42 | barRadius, 43 | labelSize, 44 | barWidth, 45 | barGap, 46 | initialDistance, 47 | verticalLabel, 48 | yAxisLegend, 49 | legendSize, 50 | showAnimation, 51 | xLegendStyles, 52 | yLegendStyles 53 | }: BarChartHookPropType) { 54 | const { fontStyle } = useDefaultFont({ labelSize }); 55 | const userAddedFont = useFont(labelFontFamily, labelSize); 56 | const font: SkFont | null = labelFontFamily ? userAddedFont : matchFont(fontStyle); 57 | const animationState = useValue(0); 58 | const canvasHeight = Math.min(screenHeight, chartHeight); 59 | const graphHeight = canvasHeight - 2 * CHART_BOTTOM_MARGIN; 60 | const xAxisData: string[] = chartData?.xAxis?.labels; 61 | const yAxisData: number[] = chartData?.yAxis?.datasets; 62 | const { 63 | windowSize, 64 | xForWindow, 65 | pointData, 66 | setPointData, 67 | xCoordinateForDataPoint, 68 | yCoordinateForDataPoint, 69 | setXForWindow, 70 | setWindowSize 71 | } = useTooltipUtils(); 72 | 73 | const yMaxRange = Math.max(...yAxisData?.map((number) => number)); 74 | const getMaxWidthLabel: number = xAxisData?.reduce((max: number, item) => { 75 | return Math.max(max, font ? font?.measureText(item).width : 0); 76 | }, 0); 77 | 78 | const getMaxHeightLabel = xAxisData?.reduce((max: number, item) => { 79 | return Math.max(max, font ? font.measureText(item).height : 0); 80 | }, 0); 81 | 82 | const canvasHeightWithHorizontalLabel = Math.floor( 83 | canvasHeight + CHART_BOTTOM_MARGIN + getMaxHeightLabel 84 | ); 85 | const canvasHeightWithVerticalLabel = Math.floor( 86 | canvasHeight + CHART_BOTTOM_MARGIN + getMaxWidthLabel 87 | ); 88 | 89 | let yScale = scaleLinear() 90 | .domain([ 91 | yAxisMin ?? 0, 92 | yAxisMax ?? Math.max(...yAxisData?.map((yDataPoint: number) => yDataPoint)) 93 | ]) 94 | .range([0, graphHeight]); 95 | 96 | const yTicks = yScale.ticks(); 97 | const yTrimmedArray = yTicks?.map((element: number) => { 98 | return element?.toString().replace('.', ''); 99 | }); 100 | 101 | const yLabelMaxLength = Math.max(...yTrimmedArray?.map((number) => String(number)?.length)); 102 | 103 | const getMaxWidthForYAxis = yTrimmedArray?.reduce((max: number, item) => { 104 | return Math.max(max, (font as SkFont)?.measureText(item.toString()).width); 105 | }, 0); 106 | 107 | if (yMaxRange > yTicks[yTicks.length - 1]) { 108 | /* `yScale` is a D3 scale function that maps the input domain (y-axis data range) to the output 109 | range (graph height). It is used to determine the vertical position of each data point on the 110 | graph. */ 111 | yScale = scaleLinear() 112 | .domain([ 113 | yAxisMin ?? 0, 114 | yAxisMax 115 | ? yAxisMax + 20 116 | : Math.max(...yAxisData.map((yDataPoint) => yDataPoint + (yTicks[1] - yTicks[0]))) 117 | ] as Iterable) 118 | .range([0, graphHeight]); 119 | } 120 | 121 | const checkXWidth = () => { 122 | const calculateXAxisWidth = barGap * xAxisData?.length + initialDistance; 123 | //TODO: find out an optimal solution to rectify the static value 2730 which is the max supported canvas width 124 | return calculateXAxisWidth > 2730 ? 2730 : barGap * xAxisData?.length; 125 | }; 126 | 127 | const xScaleBounds = [ 128 | yLabelMaxLength, 129 | barGap ? checkXWidth() - initialDistance - barWidth * 2 : chartWidth + initialDistance 130 | ]; 131 | 132 | const xScale = scalePoint() 133 | .domain(xAxisData.map((d) => d?.toString())) 134 | .range(xScaleBounds) 135 | .align(0); 136 | 137 | useEffect(() => { 138 | animate(); 139 | // eslint-disable-next-line react-hooks/exhaustive-deps 140 | }, [xAxisData, yAxisData]); 141 | 142 | const animate = () => { 143 | animationState.current = 0; 144 | runTiming(animationState, 1, { 145 | duration: showAnimation ? 1500 : 0, 146 | easing: Easing.inOut(Easing.exp) 147 | }); 148 | }; 149 | 150 | const createPath = () => { 151 | const skiaPath = Skia.Path.Make(); 152 | xAxisData?.forEach((dataPoint: string, index) => { 153 | const rect = Skia.XYWHRect( 154 | (xScale(dataPoint) as number) + yLabelMaxLength + initialDistance, 155 | graphHeight + AXIS_POSITION_VALUE, 156 | barWidth, 157 | yScale(yAxisData[index] * animationState.current) * -1 158 | ); 159 | const rRect = Skia.RRectXY(rect, barRadius, barRadius); 160 | skiaPath.addRRect(rRect); 161 | }); 162 | return skiaPath; 163 | }; 164 | 165 | const createRadius = () => { 166 | const radiusPath = Skia.Path.Make(); 167 | 168 | xAxisData?.forEach((dataPoint: string, index) => { 169 | const rect = Skia.XYWHRect( 170 | (xScale(dataPoint) as number) + yLabelMaxLength + initialDistance, 171 | graphHeight + AXIS_POSITION_VALUE, 172 | barWidth, 173 | (yScale(yAxisData[index] * animationState.current) * -1) / 2 174 | ); 175 | const rRect = Skia.RRectXY(rect, 0, 0); 176 | radiusPath.addRRect(rRect); 177 | }); 178 | return radiusPath; 179 | }; 180 | 181 | const barChartHeight: number = verticalLabel 182 | ? canvasHeightWithVerticalLabel 183 | : canvasHeightWithHorizontalLabel + INITIAL_SPACE; 184 | const barLegendHeight: number = 185 | canvasHeight - 2 * CHART_BOTTOM_MARGIN - yScale.ticks()[0] + AXIS_POSITION_VALUE; 186 | const yLabelWidth: number = yAxisLegend?.length * legendSize; 187 | const canvasWidth: number = getMaxWidthForYAxis + horizontalScale(20); 188 | const barChartWidth: number = barGap ? checkXWidth() : chartWidth + initialDistance; 189 | const xLabelPaddingLeft: number = 190 | yAxisLegend?.length * legendSize - getMaxWidthForYAxis + horizontalScale(20); 191 | const xLabelMarginLeft: number = getMaxWidthForYAxis + canvasWidth; 192 | 193 | const touchHandler = useTouchHandler( 194 | { 195 | onStart: ({ x }) => { 196 | xAxisData?.forEach((dataPoint, index) => { 197 | const xForPlottedXLabel = 198 | (xScale(dataPoint) as number) + yLabelMaxLength + initialDistance; 199 | 200 | if ( 201 | x < xForPlottedXLabel + barWidth + BARGRAPH_TOOLTIP_HITSLOP && 202 | x > xForPlottedXLabel - BARGRAPH_TOOLTIP_HITSLOP 203 | ) { 204 | setPointData({ 205 | x: dataPoint, 206 | y: yAxisData[index].toString() 207 | }); 208 | 209 | xCoordinateForDataPoint.current = 210 | (xScale(dataPoint) as number) + (yLabelMaxLength + initialDistance) + barWidth / 2; 211 | yCoordinateForDataPoint.current = 212 | windowSize.current.y - 213 | (windowSize.current.y - (graphHeight + AXIS_POSITION_VALUE)) - 214 | yScale(yAxisData[index] * animationState.current); 215 | } 216 | }); 217 | } 218 | }, 219 | [ 220 | animationState, 221 | xAxisData, 222 | chartHeight, 223 | barWidth, 224 | yAxisMin, 225 | yAxisMax, 226 | barGap, 227 | barRadius, 228 | initialDistance 229 | ] 230 | ); 231 | 232 | const path = useComputedValue(createPath, [ 233 | animationState, 234 | xAxisData, 235 | chartHeight, 236 | barWidth, 237 | yAxisMin, 238 | yAxisMax, 239 | barGap, 240 | barRadius, 241 | initialDistance 242 | ]); 243 | 244 | const radiusPath = useComputedValue(createRadius, [ 245 | animationState, 246 | xAxisData, 247 | chartHeight, 248 | barWidth, 249 | yAxisMin, 250 | yAxisMax, 251 | barGap, 252 | barRadius, 253 | initialDistance 254 | ]); 255 | 256 | const xAxisLegendStyles = { 257 | marginTop: xLegendStyles['marginTop'] ?? 0, 258 | marginBottom: xLegendStyles['marginBottom'] ?? 0, 259 | borderWidth: xLegendStyles['borderWidth'] ?? 0, 260 | borderColor: xLegendStyles['borderColor'] ?? Colors.black, 261 | marginRight: xLegendStyles['marginRight'] ?? 0, 262 | marginLeft: xLegendStyles['marginLeft'] ?? 0, 263 | color: xLegendStyles['color'] ?? Colors.black, 264 | fontWeight: xLegendStyles['fontWeight'] ?? '300', 265 | fontFamily: xLegendStyles['fontFamily'] ?? undefined 266 | }; 267 | 268 | const yAxisLegendStyles = { 269 | marginTop: yLegendStyles['marginTop'] ?? 0, 270 | marginBottom: yLegendStyles['marginBottom'] ?? 0, 271 | borderWidth: yLegendStyles['borderWidth'] ?? 0, 272 | borderColor: yLegendStyles['borderColor'] ?? Colors.black, 273 | marginRight: yLegendStyles['marginRight'] ?? 0, 274 | marginLeft: yLegendStyles['marginLeft'] ?? 0, 275 | color: yLegendStyles['color'] ?? Colors.black, 276 | fontWeight: yLegendStyles['fontWeight'] ?? '300', 277 | fontFamily: yLegendStyles['fontFamily'] ?? undefined 278 | }; 279 | 280 | return { 281 | font, 282 | xScale, 283 | path, 284 | createPath, 285 | canvasHeightWithHorizontalLabel, 286 | INITIAL_SPACE, 287 | canvasHeightWithVerticalLabel, 288 | getMaxWidthForYAxis, 289 | xAxisData, 290 | canvasHeight, 291 | CHART_BOTTOM_MARGIN, 292 | yScale, 293 | AXIS_POSITION_VALUE, 294 | yLabelMaxLength, 295 | chartWidth, 296 | barChartHeight, 297 | barLegendHeight, 298 | yLabelWidth, 299 | canvasWidth, 300 | barChartWidth, 301 | xLabelPaddingLeft, 302 | touchHandler, 303 | xForWindow, 304 | xCoordinateForDataPoint, 305 | yCoordinateForDataPoint, 306 | pointData, 307 | windowSize, 308 | setXForWindow, 309 | setWindowSize, 310 | xLabelMarginLeft, 311 | yAxisLegendStyles, 312 | xAxisLegendStyles, 313 | radiusPath 314 | }; 315 | } 316 | -------------------------------------------------------------------------------- /src/components/index.ts: -------------------------------------------------------------------------------- 1 | export * from './line-chart'; 2 | export * from './bar-chart'; 3 | -------------------------------------------------------------------------------- /src/components/line-chart/LineChart.tsx: -------------------------------------------------------------------------------- 1 | import { Canvas, Path, SkFont, matchFont, useFont } from '@shopify/react-native-skia'; 2 | import React from 'react'; 3 | import { ScrollView, View } from 'react-native'; 4 | import { DEFAULT_LABEL_SIZE } from '../../constants'; 5 | import { useDefaultFont } from '../../hooks'; 6 | import { Colors } from '../../theme'; 7 | import { Tooltip } from '../tooltip'; 8 | import styles from './LineChartStyles'; 9 | import type { LineChartPropsType, LineChartYAxisProps } from './LineChartTypes'; 10 | import { XAxisLabels, XAxisLegend, YAxisLabels, YAxisLegend, YRefLines } from './components'; 11 | import useLineChart from './useLineChart'; 12 | 13 | /** 14 | * LineChartYAxisProps represents the props for the LineChartYAxis component. 15 | * 16 | * @component LineChartYAxis - Renders the Y Axis for the LineChart Component. 17 | * @property {string} chartBackgroundColor - The background color of the chart. 18 | * @property {object} canvasStyles - The styles for the chart canvas. 19 | * @property {object} chartYAxisWidthStyle - The styles for the chart Y-axis width. 20 | * @property {React.ReactNode} children - The child components to render within the chart. 21 | */ 22 | const LineChartYAxis = ({ 23 | chartBackgroundColor, 24 | canvasStyles, 25 | chartYAxisWidthStyle, 26 | children 27 | }: LineChartYAxisProps): JSX.Element => ( 28 | 29 | {children} 30 | 31 | ); 32 | 33 | /** 34 | * LineChartPropsType represents the props for the LineChart component. 35 | * 36 | * @property {ChartDataType} chartData - The data for the chart. 37 | * @property {number} xAxisLength - The length of the X-axis. 38 | * @property {number} yAxisMin - The minimum value on the Y-axis. 39 | * @property {number} yAxisMax - The maximum value on the Y-axis. 40 | * @property {number} lineWidth - The line width. 41 | * @property {string} lineColor - The line color. 42 | * @property {number} labelSize - The font size for labels. 43 | * @property {string} labelColor - The color of labels. 44 | * @property {string} labelFontFamily - The font family for labels. 45 | * @property {number} initialDistance - The initial distance. 46 | * @property {number} verticalLabelHeight - The height of vertical labels. 47 | * @property {boolean} showLines - Whether to show grid lines. 48 | * @property {string} horizontalGridLineColor - The color of horizontal grid lines. 49 | * @property {string} chartBackgroundColor - The background color of the chart. 50 | * @property {boolean} verticalLabel - Whether to show vertical labels. 51 | * @property {string} yAxisLegend - The legend for the Y-axis. 52 | * @property {string} xAxisLegend - The legend for the X-axis. 53 | * @property {TextStyle} xLegendStyles - X Axis legend styles 54 | * @property {TextStyle} yLegendStyles - Y Axis legend styles 55 | * @property {boolean} showAnimation - Prop to handle the visibility of animation 56 | * @returns The LineChart Component to display a chart in the available metrics of the view. 57 | */ 58 | const LineChart = ({ 59 | chartData = { xAxis: { labels: [] }, yAxis: { datasets: [] } }, 60 | xAxisLength, 61 | yAxisMin, 62 | yAxisMax, 63 | lineWidth = 2, 64 | lineColor = Colors.cherryRed, 65 | labelSize = DEFAULT_LABEL_SIZE, 66 | labelColor = Colors.black, 67 | labelFontFamily, 68 | initialDistance, 69 | verticalLabelHeight, 70 | showLines = true, 71 | horizontalGridLineColor = Colors.lightgrey, 72 | chartBackgroundColor = Colors.white, 73 | verticalLabel = false, 74 | yAxisLegend = '', 75 | xAxisLegend = '', 76 | xLegendStyles = {}, 77 | yLegendStyles = {}, 78 | toolTipLabelFontSize, 79 | toolTipColor, 80 | toolTipDataColor, 81 | circularPointerColor, 82 | toolTipHorizontalPadding, 83 | toolTipFadeOutDuration, 84 | displayTooltip = false, 85 | showAnimation = true 86 | }: LineChartPropsType) => { 87 | const { fontStyle } = useDefaultFont({ labelSize: labelSize }); 88 | 89 | /** 90 | * Get the user-added font family if available, or use the matched font based on the fontStyle. 91 | * @type {SkFont | null} 92 | */ 93 | const userAddedFont: SkFont | null = useFont(labelFontFamily, labelSize); 94 | 95 | /** 96 | * The final chartFont will either be the user-added font or the matched font. 97 | * @type {SkFont | null} 98 | */ 99 | const chartFont: SkFont | null = labelFontFamily ? userAddedFont : matchFont(fontStyle); 100 | 101 | const { 102 | canvasHeight, 103 | canvasWidth, 104 | onLayout, 105 | yAxisWidth, 106 | lineAnimationState, 107 | linePath, 108 | canvasStyles, 109 | chartHeight, 110 | yScale, 111 | xScale, 112 | canvasWidthHandler, 113 | chartYAxisWidthStyle, 114 | touchHandler, 115 | xForWindow, 116 | xCoordinateForDataPoint, 117 | yCoordinateForDataPoint, 118 | pointData, 119 | windowSize, 120 | setXForWindow, 121 | setWindowSize 122 | } = useLineChart({ 123 | chartData, 124 | verticalLabel, 125 | labelSize, 126 | initialDistance, 127 | chartFont, 128 | verticalLabelHeight, 129 | xAxisLength, 130 | yAxisMin, 131 | yAxisMax, 132 | yAxisLegend, 133 | showAnimation 134 | }); 135 | 136 | return ( 137 | 140 | 141 | 149 | 156 | 157 | 158 | 159 | 168 | 169 | 179 | 190 | 200 | {displayTooltip && ( 201 | 220 | )} 221 | 222 | 223 | 224 | 225 | 234 | 235 | ); 236 | }; 237 | 238 | export default LineChart; 239 | -------------------------------------------------------------------------------- /src/components/line-chart/LineChartStyles.ts: -------------------------------------------------------------------------------- 1 | import { StyleSheet } from 'react-native'; 2 | import type { LineChartStylesType } from './LineChartTypes'; 3 | 4 | const styles = (params: LineChartStylesType = {}) => { 5 | const { chartBackgroundColor } = params; 6 | 7 | return StyleSheet.create({ 8 | chartBackgroundColor: { 9 | backgroundColor: chartBackgroundColor 10 | }, 11 | fullHeightAndWidth: { 12 | flex: 1 13 | }, 14 | chartContainer: { 15 | flex: 1, 16 | flexDirection: 'row' 17 | }, 18 | chartScrollFlex: { 19 | flex: 1, 20 | backgroundColor: chartBackgroundColor 21 | } 22 | }); 23 | }; 24 | 25 | export default styles; 26 | -------------------------------------------------------------------------------- /src/components/line-chart/LineChartTypes.ts: -------------------------------------------------------------------------------- 1 | import type { 2 | AnimatedProp, 3 | Color, 4 | DataSourceParam, 5 | SkFont, 6 | SkPath, 7 | SkiaMutableValue, 8 | SkiaValue 9 | } from '@shopify/react-native-skia'; 10 | import type { ScaleLinear, ScalePoint } from 'd3-scale'; 11 | import type { MutableRefObject } from 'react'; 12 | import type { 13 | ColorValue, 14 | LayoutChangeEvent, 15 | NativeScrollEvent, 16 | StyleProp, 17 | TextStyle, 18 | ViewStyle 19 | } from 'react-native'; 20 | import type { ChartDataType, Range } from '../bar-chart'; 21 | import type { PointDataType, SetWindowSizeArgsType, WindowSizeDataType } from '../tooltip'; 22 | 23 | export type ScaledDataType = Array<{ x: number; y: number }>; 24 | 25 | export interface CommonLineChartTypes { 26 | chartData: ChartDataType; 27 | verticalLabel?: boolean; 28 | labelSize?: number; 29 | initialDistance?: number; 30 | verticalLabelHeight?: number; 31 | xAxisLength?: Range<1, 999>; 32 | yAxisMin?: number; 33 | yAxisMax?: number; 34 | showAnimation?: boolean; 35 | } 36 | 37 | export interface LineChartHookPropsType extends CommonLineChartTypes { 38 | chartFont: SkFont | null; 39 | yAxisLegend?: string; 40 | } 41 | 42 | export interface LineChartHookReturnType { 43 | canvasHeight: number; 44 | canvasWidth: number; 45 | onLayout: (event: LayoutChangeEvent) => void; 46 | lineAnimationState: SkiaMutableValue; 47 | yAxisWidth: number; 48 | maxWidthXLabel: number; 49 | linePath: SkiaValue; 50 | canvasStyles: StyleProp; 51 | chartHeight: number; 52 | yScale: ScaleLinear; 53 | xScale: ScalePoint; 54 | canvasWidthHandler: number; 55 | chartYAxisWidthStyle: StyleProp; 56 | touchHandler: any; 57 | xForWindow: MutableRefObject; 58 | xCoordinateForDataPoint: SkiaMutableValue; 59 | yCoordinateForDataPoint: SkiaMutableValue; 60 | pointData: PointDataType; 61 | windowSize: MutableRefObject; 62 | setXForWindow: ({ nativeEvent }: { nativeEvent: NativeScrollEvent }) => void; 63 | setWindowSize: ({ nativeEvent }: SetWindowSizeArgsType) => void; 64 | } 65 | 66 | export interface LineChartPropsType extends CommonLineChartTypes { 67 | lineWidth?: AnimatedProp>; 68 | labelColor?: Color; 69 | showLines?: boolean; 70 | lineColor?: Color; 71 | labelFontFamily?: DataSourceParam; 72 | horizontalGridLineColor?: Color; 73 | chartBackgroundColor?: ColorValue; 74 | yAxisLegend?: string; 75 | xAxisLegend?: string; 76 | xLegendStyles?: TextStyle; 77 | yLegendStyles?: TextStyle; 78 | toolTipLabelFontSize?: number; 79 | toolTipColor?: string; 80 | toolTipDataColor?: string; 81 | circularPointerColor?: string; 82 | toolTipHorizontalPadding?: number; 83 | toolTipFadeOutDuration?: number; 84 | displayTooltip?: boolean; 85 | } 86 | 87 | export type LineChartYAxisProps = { 88 | chartBackgroundColor: ColorValue; 89 | canvasStyles: StyleProp; 90 | chartYAxisWidthStyle: StyleProp; 91 | children: React.ReactElement; 92 | }; 93 | 94 | export type LineChartStylesType = 95 | | Partial<{ 96 | chartBackgroundColor: ColorValue; 97 | xAxisLegendWidth: number; 98 | }> 99 | | undefined; 100 | -------------------------------------------------------------------------------- /src/components/line-chart/components/index.ts: -------------------------------------------------------------------------------- 1 | export * from './x-axis-labels'; 2 | export * from './x-axis-legend'; 3 | export * from './y-axis-labels'; 4 | export * from './y-axis-legend'; 5 | export * from './y-ref-lines'; 6 | -------------------------------------------------------------------------------- /src/components/line-chart/components/x-axis-labels/XAxisLabelTypes.ts: -------------------------------------------------------------------------------- 1 | import type { Color, SkFont } from '@shopify/react-native-skia'; 2 | import type { ScalePoint } from 'd3-scale'; 3 | 4 | export type XAxisLabelsPropsType = { 5 | canvasHeight: number; 6 | chartFont: SkFont | null; 7 | chartHeight: number; 8 | labelColor: Color; 9 | labelSize: number; 10 | verticalLabel: boolean; 11 | xScale: ScalePoint; 12 | }; 13 | -------------------------------------------------------------------------------- /src/components/line-chart/components/x-axis-labels/XAxisLabels.tsx: -------------------------------------------------------------------------------- 1 | import { Group, Text } from '@shopify/react-native-skia'; 2 | import React from 'react'; 3 | import { Y_AXIS_LABEL_HORIZONTAL_GAP } from '../../../../constants'; 4 | import type { XAxisLabelsPropsType } from './XAxisLabelTypes'; 5 | 6 | /** 7 | * Component to render X-axis labels. 8 | * 9 | * @param {XAxisLabelsPropsType} props - The component's props. 10 | * @param {number} props.canvasHeight - Height of the canvas. 11 | * @param {number} props.chartFont - The font to display for labels. 12 | * @param {string} props.chartHeight - The height of the chart to be displayed. 13 | * @param {number} props.labelColor - Color of the axis labels. 14 | * @param {number} props.labelSize - Size of the axis labels. 15 | * @param {string} props.verticalLabel - Prop to handle text rotation. 16 | * @param {number} props.xScale - The scaled data of the labels. 17 | * @returns {JSX.Element} - The rendered X-axis labels. 18 | */ 19 | const XAxisLabels = ({ 20 | canvasHeight, 21 | chartFont, 22 | chartHeight, 23 | labelColor, 24 | labelSize, 25 | verticalLabel, 26 | xScale 27 | }: XAxisLabelsPropsType): JSX.Element => ( 28 | 29 | {xScale.domain().map((label: string, idx: number) => { 30 | // Measure the label's length for horizontal positioning 31 | const labelLength = chartFont?.measureText(label); 32 | // Calculate x and y positions based on label and orientation 33 | const xPosition = 34 | (xScale(label) ?? 0) - 35 | (verticalLabel 36 | ? labelLength?.width! + Y_AXIS_LABEL_HORIZONTAL_GAP 37 | : label.length * (labelSize / 4)); 38 | const yPosition = verticalLabel ? chartHeight : canvasHeight - labelSize / 2; 39 | 40 | return ( 41 | 54 | ); 55 | })} 56 | 57 | ); 58 | 59 | export default XAxisLabels; 60 | -------------------------------------------------------------------------------- /src/components/line-chart/components/x-axis-labels/index.ts: -------------------------------------------------------------------------------- 1 | export { default as XAxisLabels } from './XAxisLabels'; 2 | -------------------------------------------------------------------------------- /src/components/line-chart/components/x-axis-legend/XAxisLegend.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Text, View } from 'react-native'; 3 | import styles from './XAxisLegendStyles'; 4 | import type { XAxisLegendPropsType } from './XAxisLegendTypes'; 5 | 6 | /** 7 | * XAxisLegend component renders the legend for the X-axis. 8 | * 9 | * @component 10 | * @param {XAxisLegendPropsType} props - The properties of the XAxisLegend component. 11 | * @param {number} props.canvasWidth - Width of the canvas. 12 | * @param {number} props.yAxisWidth - Width of the Y-axis. 13 | * @param {number} props.labelSize - Size of the axis labels. 14 | * @param {string} props.xAxisLegend - Text to display as X-axis legend. 15 | * @param {TextStyle} props.xLegendStyles - Styles object for XLegend 16 | * @returns {JSX.Element} XAxisLegend component. 17 | */ 18 | const XAxisLegend = ({ 19 | canvasWidth, 20 | yAxisWidth, 21 | labelSize, 22 | xAxisLegend, 23 | xLegendStyles 24 | }: XAxisLegendPropsType): JSX.Element => { 25 | const xAxisLegendWidth = 26 | canvasWidth - yAxisWidth * 10 - (xLegendStyles?.fontSize ?? labelSize) * 2; 27 | 28 | // Render X-axis legend if it has content 29 | if (xAxisLegend.length > 0) { 30 | return ( 31 | 32 | 41 | {xAxisLegend} 42 | 43 | 44 | ); 45 | } 46 | 47 | // If X-axis legend is empty, return an empty fragment 48 | return <>; 49 | }; 50 | 51 | export default XAxisLegend; 52 | -------------------------------------------------------------------------------- /src/components/line-chart/components/x-axis-legend/XAxisLegendStyles.ts: -------------------------------------------------------------------------------- 1 | import { StyleSheet } from 'react-native'; 2 | import type { xLegendStylesType } from './XAxisLegendTypes'; 3 | import { DEFAULT_LABEL_SIZE } from '../../../../constants'; 4 | 5 | const styles = (params: xLegendStylesType = {}) => { 6 | const { labelSize = DEFAULT_LABEL_SIZE, xAxisLegendWidth, xLegendStyles } = params; 7 | 8 | return StyleSheet.create({ 9 | xAxisLegendContainer: { 10 | alignSelf: 'flex-end', 11 | width: xAxisLegendWidth 12 | }, 13 | xAxisLegendText: { 14 | alignSelf: 'center', 15 | textAlign: 'center', 16 | fontSize: xLegendStyles?.fontSize ?? labelSize - 2, 17 | ...xLegendStyles 18 | } 19 | }); 20 | }; 21 | 22 | export default styles; 23 | -------------------------------------------------------------------------------- /src/components/line-chart/components/x-axis-legend/XAxisLegendTypes.ts: -------------------------------------------------------------------------------- 1 | import type { TextStyle } from 'react-native'; 2 | 3 | export type XAxisLegendPropsType = { 4 | canvasWidth: number; 5 | yAxisWidth: number; 6 | labelSize: number; 7 | xAxisLegend: string; 8 | xLegendStyles?: TextStyle; 9 | }; 10 | 11 | export type xLegendStylesType = 12 | | Partial<{ 13 | xAxisLegendWidth: number; 14 | labelSize: number; 15 | xLegendStyles?: TextStyle; 16 | }> 17 | | undefined; 18 | -------------------------------------------------------------------------------- /src/components/line-chart/components/x-axis-legend/index.ts: -------------------------------------------------------------------------------- 1 | export { default as XAxisLegend } from './XAxisLegend'; 2 | -------------------------------------------------------------------------------- /src/components/line-chart/components/y-axis-labels/YAxisLabels.tsx: -------------------------------------------------------------------------------- 1 | import { Group, Text } from '@shopify/react-native-skia'; 2 | import React from 'react'; 3 | import type { YAxisLabelsPropsType } from './YAxisLabelsTypes'; 4 | 5 | /** 6 | * Renders Y-axis labels for a chart. 7 | * 8 | * @param {YAxisLabelsPropsType} props - The component's props. 9 | * @param {number} props.yScale - The y-axis scale function. 10 | * @param {string} props.labelColor - The color of the labels. 11 | * @param {string} props.chartFont - The font for the labels. 12 | * @returns {JSX.Element} - A React element representing the Y-axis labels. 13 | */ 14 | const YAxisLabels = ({ 15 | yScale, 16 | labelColor, 17 | chartFont, 18 | }: YAxisLabelsPropsType): JSX.Element => ( 19 | 20 | {yScale.ticks(6).map((label: number, idx: number) => { 21 | const yPoint = yScale(label); 22 | return ( 23 | 31 | ); 32 | })} 33 | 34 | ); 35 | 36 | export default YAxisLabels; 37 | -------------------------------------------------------------------------------- /src/components/line-chart/components/y-axis-labels/YAxisLabelsTypes.ts: -------------------------------------------------------------------------------- 1 | import type { Color, SkFont } from '@shopify/react-native-skia'; 2 | import type { ScaleLinear } from 'd3-scale'; 3 | 4 | export type YAxisLabelsPropsType = { 5 | yScale: ScaleLinear; 6 | labelColor: Color; 7 | chartFont: SkFont | null; 8 | }; 9 | -------------------------------------------------------------------------------- /src/components/line-chart/components/y-axis-labels/index.ts: -------------------------------------------------------------------------------- 1 | export { default as YAxisLabels } from './YAxisLabels'; 2 | -------------------------------------------------------------------------------- /src/components/line-chart/components/y-axis-legend/YAxisLegend.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Text, View } from 'react-native'; 3 | import type { YAxisLegendPropsType } from './YAxisLegendTypes'; 4 | import styles from './YAxisLegendStyles'; 5 | import { DEFAULT_LABEL_SIZE } from '../../../../constants'; 6 | 7 | /** 8 | * YAxisLegend component displays the legend on the Y-axis. 9 | * 10 | * @param {YAxisLegendPropsType} props - The component's props. 11 | * @param {number} props.labelSize - Font size for the label. 12 | * @param {number} props.chartHeight - Height of the chart. 13 | * @param {string} props.yAxisLegend - The Y-axis legend text. 14 | * @param {TextStyle} props.yLegendStyles - Styles object for YLegend 15 | * @returns {JSX.Element} The YAxisLegend component. 16 | */ 17 | const YAxisLegend = ({ 18 | labelSize = DEFAULT_LABEL_SIZE, 19 | chartHeight, 20 | yAxisLegend, 21 | yLegendStyles 22 | }: YAxisLegendPropsType): JSX.Element => { 23 | const yAxisLegendRotatedWidth = yAxisLegend?.length * (yLegendStyles?.fontSize ?? labelSize); 24 | 25 | // Check if there is Y-axis legend text to display 26 | if (yAxisLegend.length > 0) { 27 | return ( 28 | 36 | 37 | {yAxisLegend} 38 | 39 | 40 | ); 41 | } 42 | 43 | // If no Y-axis legend text is available, return an empty component 44 | return <>; 45 | }; 46 | 47 | export default YAxisLegend; 48 | -------------------------------------------------------------------------------- /src/components/line-chart/components/y-axis-legend/YAxisLegendStyles.ts: -------------------------------------------------------------------------------- 1 | import { StyleSheet } from 'react-native'; 2 | import type { YLegendStylesType } from './YAxisLegendTypes'; 3 | import { DEFAULT_LABEL_SIZE } from '../../../../constants'; 4 | 5 | const styles = (params: YLegendStylesType = {}) => { 6 | const { 7 | labelSize = DEFAULT_LABEL_SIZE, 8 | chartHeight, 9 | yAxisLegendRotatedWidth, 10 | yLegendStyles 11 | } = params; 12 | 13 | return StyleSheet.create({ 14 | yAxisLegendContainer: { 15 | justifyContent: 'center', 16 | alignItems: 'center', 17 | overflow: 'hidden', 18 | width: (yLegendStyles?.fontSize ?? labelSize) * 2, 19 | height: chartHeight, 20 | marginLeft: yLegendStyles?.marginLeft, 21 | marginRight: yLegendStyles?.marginRight 22 | }, 23 | yAxisLegendRotation: { 24 | justifyContent: 'center', 25 | alignItems: 'center', 26 | transform: [{ rotate: '-90deg' }], 27 | width: yAxisLegendRotatedWidth 28 | }, 29 | yAxisLegendText: { 30 | fontSize: yLegendStyles?.fontSize ?? labelSize - 2, 31 | ...yLegendStyles 32 | } 33 | }); 34 | }; 35 | 36 | export default styles; 37 | -------------------------------------------------------------------------------- /src/components/line-chart/components/y-axis-legend/YAxisLegendTypes.ts: -------------------------------------------------------------------------------- 1 | import type { TextStyle } from 'react-native'; 2 | 3 | export type YAxisLegendCommonTypes = Partial<{ 4 | chartHeight: number; 5 | labelSize: number; 6 | yLegendStyles: TextStyle; 7 | }>; 8 | 9 | export type YAxisLegendPropsType = YAxisLegendCommonTypes & { 10 | yAxisLegend: string; 11 | }; 12 | 13 | export type YLegendStylesType = 14 | | (YAxisLegendCommonTypes & { 15 | yAxisLegendRotatedWidth?: number; 16 | }) 17 | | undefined; 18 | -------------------------------------------------------------------------------- /src/components/line-chart/components/y-axis-legend/index.ts: -------------------------------------------------------------------------------- 1 | export { default as YAxisLegend } from './YAxisLegend'; 2 | -------------------------------------------------------------------------------- /src/components/line-chart/components/y-ref-lines/YRefLines.tsx: -------------------------------------------------------------------------------- 1 | import { DashPathEffect, Group, Path } from '@shopify/react-native-skia'; 2 | import React from 'react'; 3 | import type { YRefLinePropsType } from './YRefLinesTypes'; 4 | 5 | /** 6 | * Renders horizontal reference lines on the Y-axis based on the provided scale and configuration. 7 | * 8 | * @component 9 | * @param {YRefLinePropsType} props - The properties for YRefLines component. 10 | * @param {function} props.yScale - Function to calculate Y-axis values based on data. 11 | * @param {boolean} props.showLines - Flag to determine whether to show reference lines. 12 | * @param {string} props.horizontalGridLineColor - Color of the horizontal grid lines. 13 | * @param {Array} props.xScaleBounds - X-axis scale bounds. 14 | * @param {number} props.canvasWidth - Width of the canvas. 15 | * @param {number} props.xAxisLength - Length of the X-axis. 16 | * @param {function} props.canvasWidthHandler - Function to handle canvas width changes. 17 | * @returns {JSX.Element} - Rendered YRefLines component. 18 | */ 19 | const YRefLines = ({ 20 | yScale, 21 | showLines, 22 | horizontalGridLineColor, 23 | canvasWidth, 24 | xAxisLength, 25 | canvasWidthHandler 26 | }: YRefLinePropsType): JSX.Element => { 27 | // If showLines is false, render nothing 28 | if (!showLines) { 29 | return <>; 30 | } 31 | 32 | // Render horizontal reference lines based on Y-scale ticks 33 | return ( 34 | 35 | {yScale.ticks(6).map((label: number, idx: number) => { 36 | // Calculate Y-coordinate for the current tick label 37 | const yPoint = yScale(label); 38 | // Render dashed horizontal line 39 | return ( 40 | 47 | 48 | 49 | ); 50 | })} 51 | 52 | ); 53 | }; 54 | 55 | export default YRefLines; 56 | -------------------------------------------------------------------------------- /src/components/line-chart/components/y-ref-lines/YRefLinesTypes.ts: -------------------------------------------------------------------------------- 1 | import type { Color } from '@shopify/react-native-skia'; 2 | import type { ScaleLinear } from 'd3-scale'; 3 | 4 | export type YRefLinePropsType = { 5 | canvasWidth: number; 6 | horizontalGridLineColor: Color; 7 | showLines: boolean; 8 | xAxisLength?: number; 9 | yScale: ScaleLinear; 10 | canvasWidthHandler: number; 11 | }; 12 | -------------------------------------------------------------------------------- /src/components/line-chart/components/y-ref-lines/index.ts: -------------------------------------------------------------------------------- 1 | export { default as YRefLines } from './YRefLines'; 2 | -------------------------------------------------------------------------------- /src/components/line-chart/index.ts: -------------------------------------------------------------------------------- 1 | export { default as LineChart } from './LineChart'; 2 | export * from './LineChartTypes'; 3 | -------------------------------------------------------------------------------- /src/components/line-chart/useLineChart.ts: -------------------------------------------------------------------------------- 1 | import { 2 | runTiming, 3 | SkiaMutableValue, 4 | SkiaValue, 5 | SkPath, 6 | useComputedValue, 7 | useTouchHandler, 8 | useValue 9 | } from '@shopify/react-native-skia'; 10 | import { scaleLinear, scalePoint, type ScaleLinear, type ScalePoint } from 'd3-scale'; 11 | import React, { useCallback, useEffect, useState } from 'react'; 12 | import type { LayoutChangeEvent, StyleProp, ViewStyle } from 'react-native'; 13 | import { 14 | CHART_X_LABEL_HEIGHT_RECTIFIER, 15 | DEFAULT_LABEL_SIZE, 16 | LINE_ANIMATION_TIME, 17 | X_AXIS_LABEL_WIDTH_RECTIFIER, 18 | Y_AXIS_LABEL_HORIZONTAL_GAP, 19 | Y_AXIS_LEGEND_FALSE_VALUE, 20 | Y_AXIS_LEGEND_TRUE_VALUE 21 | } from '../../constants'; 22 | import { 23 | calculateCanvasWidth, 24 | calculateMaxWidthLabel, 25 | findMaxNumber, 26 | generateLinePath 27 | } from '../../utils'; 28 | import { useTooltipUtils } from '../tooltip'; 29 | import type { 30 | LineChartHookPropsType, 31 | LineChartHookReturnType, 32 | ScaledDataType 33 | } from './LineChartTypes'; 34 | 35 | /** 36 | * Reference to handle the line animation. 37 | * @type {React.MutableRefObject} 38 | */ 39 | const isLineAnimationRunning: React.MutableRefObject = React.createRef(); 40 | 41 | /** 42 | * Custom hook for creating a line chart. 43 | * @param {LineChartHookPropsType} props - The properties for the line chart. 44 | * @returns {LineChartHookReturnType} An object containing various chart-related properties and functions. 45 | */ 46 | const useLineChart = ({ 47 | chartData, 48 | verticalLabel, 49 | labelSize = DEFAULT_LABEL_SIZE, 50 | initialDistance, 51 | chartFont, 52 | verticalLabelHeight, 53 | xAxisLength, 54 | yAxisMin, 55 | yAxisMax, 56 | yAxisLegend, 57 | showAnimation 58 | }: LineChartHookPropsType): LineChartHookReturnType => { 59 | const data = chartData.yAxis.datasets; 60 | const maxYAxisNumberValue = findMaxNumber(data); 61 | const yAxisWidth = maxYAxisNumberValue.toString().length ?? 0; 62 | 63 | const [canvasWidth, setCanvasWidth] = useState(0); 64 | const [canvasHeight, setCanvasHeight] = useState(0); 65 | 66 | const { 67 | windowSize, 68 | xForWindow, 69 | pointData, 70 | setPointData, 71 | xCoordinateForDataPoint, 72 | yCoordinateForDataPoint, 73 | setXForWindow, 74 | setWindowSize 75 | } = useTooltipUtils(); 76 | 77 | /** 78 | * Value to manipulate the line drawing path. 79 | * @type {SkiaMutableValue} 80 | */ 81 | const lineAnimationState: SkiaMutableValue = useValue(0); 82 | 83 | /** 84 | * Calculates the maximum width of X-axis labels. 85 | * @type {number} 86 | */ 87 | const maxWidthXLabel: number = calculateMaxWidthLabel(chartData.xAxis.labels, chartFont); 88 | 89 | /** 90 | * Function to handle the layout event. 91 | * @param {LayoutChangeEvent} event - The layout change event. 92 | */ 93 | const onLayout = useCallback( 94 | ({ nativeEvent: { layout } }: LayoutChangeEvent) => { 95 | setCanvasWidth(Math.round(layout.width)); 96 | setCanvasHeight(Math.round(layout.height)); 97 | }, 98 | // eslint-disable-next-line react-hooks/exhaustive-deps 99 | [] 100 | ); 101 | 102 | /** 103 | * Function to animate the line. 104 | */ 105 | const animateLine = () => { 106 | lineAnimationState.current = showAnimation ? 0 : 1; 107 | runTiming(lineAnimationState, 1, { duration: LINE_ANIMATION_TIME }, () => { 108 | isLineAnimationRunning.current = false; 109 | }); 110 | }; 111 | 112 | // Trigger the animation when the component mounts. 113 | useEffect(() => { 114 | isLineAnimationRunning.current = false; 115 | let lineAnimationTimeout: NodeJS.Timeout; 116 | 117 | if (!isLineAnimationRunning.current) { 118 | lineAnimationState.current = 0; 119 | isLineAnimationRunning.current = true; 120 | lineAnimationTimeout = setTimeout(animateLine, 0); 121 | } 122 | 123 | // Clearing out the timeout. 124 | return () => { 125 | lineAnimationTimeout && clearTimeout(lineAnimationTimeout); 126 | }; 127 | // eslint-disable-next-line react-hooks/exhaustive-deps 128 | }, [data]); 129 | 130 | /** 131 | * Calculates the canvas width. 132 | * @type {number} 133 | */ 134 | const canvasWidthHandler: number = calculateCanvasWidth( 135 | xAxisLength, 136 | initialDistance, 137 | data.length 138 | ); 139 | 140 | /** 141 | * Calculates the height of the chart. 142 | * @type {number} 143 | */ 144 | const chartHeight: number = verticalLabel 145 | ? canvasHeight - (verticalLabelHeight ? verticalLabelHeight : maxWidthXLabel + 5) 146 | : canvasHeight - labelSize * CHART_X_LABEL_HEIGHT_RECTIFIER; 147 | 148 | /** 149 | * Value to handle the width fo the Graph when Y-Axis-Legend is Passed 150 | */ 151 | const labelLengthValueMultiplier = yAxisLegend 152 | ? Y_AXIS_LEGEND_TRUE_VALUE 153 | : Y_AXIS_LEGEND_FALSE_VALUE; 154 | 155 | /** 156 | * Defines the bounds for the x-scale. 157 | * @type {[number, number]} 158 | */ 159 | const xScaleBounds: [number, number] = [ 160 | initialDistance ?? findMaxNumber(data).toString().length + Y_AXIS_LABEL_HORIZONTAL_GAP, 161 | xAxisLength 162 | ? canvasWidthHandler - (initialDistance ?? 0) 163 | : canvasWidth - 164 | yAxisWidth * X_AXIS_LABEL_WIDTH_RECTIFIER - 165 | labelSize * 1.5 * labelLengthValueMultiplier 166 | ]; 167 | 168 | /** 169 | * Defines the bounds for the y-scale. 170 | * @type {[number, number]} 171 | */ 172 | const yScaleBounds: [number, number] = [chartHeight, labelSize * 1.5]; 173 | 174 | /** 175 | * Defines the domain for the y-scale. 176 | * @type {[number, number]} 177 | */ 178 | const yScaleDomain: [number, number] = [yAxisMin ?? 0, yAxisMax ?? Math.max(...data)]; 179 | 180 | /** 181 | * Creates the y-scale. 182 | * @type {ScaleLinear} 183 | */ 184 | const yScale: ScaleLinear = scaleLinear() 185 | .domain(yScaleDomain) 186 | .range(yScaleBounds); 187 | 188 | /** 189 | * Creates the x-scale. 190 | * @type {ScalePoint} 191 | */ 192 | const xScale: ScalePoint = scalePoint() 193 | .domain(chartData.xAxis.labels?.map((d) => d)) 194 | .range(xScaleBounds) 195 | .align(0); 196 | 197 | /** 198 | * Scales the chart data for plotting graph. 199 | * @type {ScaledDataType} 200 | */ 201 | const scaledData: ScaledDataType = chartData.xAxis.labels.map((x, index) => ({ 202 | x: xScale(x) ?? 0, 203 | y: yScale(data[index]) 204 | })); 205 | 206 | /** 207 | * The width of the screen canvas, which is calculated based on various factors. 208 | * @type {number} 209 | * @description This constant represents the width of the screen canvas and is determined by subtracting a combination 210 | * of values from the `canvasWidth`. It is calculated as follows: 211 | * - Subtracting `yAxisWidth * 10`: This accounts for the width taken by the yAxis content, multiplied by 10 units. 212 | * - Subtracting `labelSize * 1.5 * (yAxisLegend ? 3 : 0.5)`: This accounts for the width taken by labels, which 213 | * is multiplied by 1.5 units and further adjusted based on whether `yAxisLegend` is true (multiplied by 3) or 214 | * false (multiplied by 0.5). 215 | * 216 | * */ 217 | const screenCanvasWidth: number = 218 | canvasWidth - yAxisWidth * 10 - labelSize * 1.5 * (yAxisLegend ? 3 : 0.5); 219 | 220 | /** 221 | * Defines styles for the canvas. 222 | * @type {StyleProp} 223 | */ 224 | const canvasStyles: StyleProp = { 225 | width: xAxisLength ? canvasWidthHandler : screenCanvasWidth, 226 | height: canvasHeight 227 | }; 228 | 229 | /** 230 | * Defines styles for the y-axis width. 231 | * @type {StyleProp } 232 | */ 233 | const chartYAxisWidthStyle: StyleProp = { 234 | // The below multiplier allow larger label size and more space. 235 | // Magic Number: 1.3 is divided to handle the extra spacing in Axis Width. 236 | width: (yAxisWidth * labelSize) / 1.3 237 | }; 238 | 239 | /** 240 | * Generates the line path using computed values. 241 | * @type {SkiaValue} 242 | */ 243 | const linePath: SkiaValue = useComputedValue( 244 | () => generateLinePath(scaledData), 245 | [scaledData] 246 | ); 247 | 248 | /** 249 | * Touch handler function that responds to touch events on the chart. 250 | * 251 | * @param {Object} options - Options for touch handling. 252 | * @param {Function} options.onStart - Callback function triggered when touch starts. 253 | * @param {Object} options.onStartParams - Parameters for the onStart callback. 254 | * @param {number} options.onStartParams.x - The x-coordinate of the touch point. 255 | */ 256 | const touchHandler = useTouchHandler( 257 | { 258 | onStart: ({ x }) => { 259 | // Finds the closest point x-point from the point at which the users touches on the chart 260 | const closestX = xScale.domain().reduce((prev, curr) => { 261 | return Math.abs((xScale(curr) as number) - x) < Math.abs((xScale(prev) as number) - x) 262 | ? curr 263 | : prev; 264 | }); 265 | 266 | /** 267 | * Finds the Y value for the given X value. 268 | * 269 | * @param {string} targetX - The target X value for which to find the Y value. 270 | * @returns {number} - The Y value corresponding to the given X value. 271 | */ 272 | const findYValueForX = (targetX: string): number => { 273 | const xValueIndex = chartData?.xAxis?.labels?.findIndex((e) => e == targetX?.toString()); 274 | return chartData?.yAxis?.datasets?.[xValueIndex]; // Return 0 if the value of x is not found in the array. 275 | }; 276 | 277 | // Finds the Y value for the X-value found from user's touch input 278 | const closestY = findYValueForX(closestX); 279 | 280 | // Set X and Y coordinates of the closest data point on chart 281 | xScale.domain().forEach((item) => { 282 | if (item === closestX) { 283 | xCoordinateForDataPoint.current = xScale(item) as number; 284 | } 285 | }); 286 | yCoordinateForDataPoint.current = yScale(closestY); 287 | 288 | /** 289 | * Sets the data for the closest point on the chart. 290 | * 291 | * @param {Object} data - Data for the closest point. 292 | * @param {string} data.x - The X value of the closest point. 293 | * @param {string} data.y - The Y value of the closest point as a string. 294 | */ 295 | setPointData({ 296 | x: closestX, 297 | y: closestY?.toString() 298 | }); 299 | } 300 | }, 301 | [xScaleBounds] 302 | ); 303 | 304 | return { 305 | canvasHeight, 306 | canvasWidth, 307 | onLayout, 308 | lineAnimationState, 309 | yAxisWidth, 310 | maxWidthXLabel, 311 | linePath, 312 | canvasStyles, 313 | chartHeight, 314 | yScale, 315 | xScale, 316 | canvasWidthHandler, 317 | chartYAxisWidthStyle, 318 | touchHandler, 319 | xForWindow, 320 | xCoordinateForDataPoint, 321 | yCoordinateForDataPoint, 322 | pointData, 323 | windowSize, 324 | setXForWindow, 325 | setWindowSize 326 | }; 327 | }; 328 | 329 | export default useLineChart; 330 | -------------------------------------------------------------------------------- /src/components/tooltip/Tooltip.tsx: -------------------------------------------------------------------------------- 1 | import { Circle, Group, Path, RoundedRect, Text } from '@shopify/react-native-skia'; 2 | import React from 'react'; 3 | import { Colors } from '../../theme'; 4 | import type { TooltipPropsType } from './TooltipTypes'; 5 | import useTooltip from './useTooltip'; 6 | import { 7 | TOOLTIP_BORDER_RADIUS_RECTIFIER, 8 | TOOLTIP_DATA_POINT_CIRCLE_RECTIFIER 9 | } from '../../constants'; 10 | 11 | const Tooltip = ({ 12 | xCoordinateForDataPoint, 13 | yCoordinateForDataPoint, 14 | pointData, 15 | labelFontFamily, 16 | xAxisLegend, 17 | yAxisLegend, 18 | windowSize, 19 | xForWindow, 20 | toolTipLabelFontSize, 21 | toolTipColor = Colors.red, 22 | toolTipDataColor = Colors.white, 23 | circularPointerColor = Colors.black, 24 | displayCircularPointer = false, 25 | toolTipHorizontalPadding, 26 | toolTipFadeOutDuration 27 | }: TooltipPropsType) => { 28 | const { 29 | font, 30 | xCordForRoundedRect, 31 | yCordForRoundedRect, 32 | tooltipWidth, 33 | xCordForTopText, 34 | path, 35 | yCordForTopText, 36 | xCordForBottomText, 37 | yCordForBottomText, 38 | tooltipHeight, 39 | opacity, 40 | labelForX, 41 | labelForY 42 | } = useTooltip({ 43 | labelFontFamily, 44 | xAxisLegend, 45 | pointData, 46 | yAxisLegend, 47 | xCoordinateForDataPoint, 48 | yCoordinateForDataPoint, 49 | toolTipLabelFontSize, 50 | xForWindow, 51 | windowSize, 52 | toolTipHorizontalPadding, 53 | toolTipFadeOutDuration 54 | }); 55 | 56 | if (font === null) { 57 | return <>; 58 | } 59 | 60 | if (pointData.x === '0' && pointData.y === '0') return <>; 61 | 62 | return ( 63 | 64 | 72 | 73 | 80 | 87 | {displayCircularPointer && ( 88 | 94 | )} 95 | 96 | ); 97 | }; 98 | 99 | export default Tooltip; 100 | -------------------------------------------------------------------------------- /src/components/tooltip/TooltipTypes.ts: -------------------------------------------------------------------------------- 1 | import type { DataSourceParam, SkiaValue } from '@shopify/react-native-skia'; 2 | import type { MutableRefObject } from 'react'; 3 | import type { LayoutRectangle } from 'react-native'; 4 | 5 | type WindowSizeDataType = { 6 | x: number; 7 | y: number; 8 | }; 9 | 10 | type WindowSizeType = MutableRefObject; 11 | 12 | type PointDataType = { 13 | x: string; 14 | y: string; 15 | }; 16 | 17 | type SetWindowSizeArgsType = { 18 | nativeEvent: { 19 | layout: LayoutRectangle; 20 | }; 21 | }; 22 | 23 | interface TooltipPropsType { 24 | yCoordinateForDataPoint: SkiaValue; 25 | xCoordinateForDataPoint: SkiaValue; 26 | pointData: PointDataType; 27 | labelFontFamily?: DataSourceParam; 28 | xAxisLegend: string; 29 | yAxisLegend: string; 30 | windowSize: WindowSizeType; 31 | xForWindow: number; 32 | toolTipColor?: string; 33 | toolTipDataColor?: string; 34 | circularPointerColor?: string; 35 | toolTipLabelFontSize?: number; 36 | displayCircularPointer?: boolean; 37 | toolTipHorizontalPadding?: number; 38 | toolTipFadeOutDuration?: number; 39 | } 40 | 41 | interface UseTooltipPropsType { 42 | labelFontFamily?: DataSourceParam; 43 | xAxisLegend: string; 44 | yAxisLegend: string; 45 | pointData: PointDataType; 46 | xCoordinateForDataPoint: SkiaValue; 47 | yCoordinateForDataPoint: SkiaValue; 48 | xForWindow: number; 49 | windowSize: WindowSizeType; 50 | toolTipLabelFontSize?: number; 51 | toolTipHorizontalPadding?: number; 52 | toolTipFadeOutDuration?: number; 53 | } 54 | 55 | export type { 56 | TooltipPropsType, 57 | WindowSizeType, 58 | UseTooltipPropsType, 59 | PointDataType, 60 | WindowSizeDataType, 61 | SetWindowSizeArgsType 62 | }; 63 | -------------------------------------------------------------------------------- /src/components/tooltip/index.ts: -------------------------------------------------------------------------------- 1 | export { default as Tooltip } from './Tooltip'; 2 | export { default as useTooltipUtils } from './useTooltipUtils'; 3 | export * from './TooltipTypes'; 4 | -------------------------------------------------------------------------------- /src/components/tooltip/useTooltip.ts: -------------------------------------------------------------------------------- 1 | import { 2 | interpolate, 3 | matchFont, 4 | runTiming, 5 | SkFont, 6 | Skia, 7 | SkiaValue, 8 | useComputedValue, 9 | useFont, 10 | useValue 11 | } from '@shopify/react-native-skia'; 12 | import { useEffect } from 'react'; 13 | import { useDefaultFont } from '../../hooks'; 14 | import { horizontalScale, moderateScale, verticalScale } from '../../theme'; 15 | import type { UseTooltipPropsType } from './TooltipTypes'; 16 | 17 | const useTooltip = ({ 18 | labelFontFamily, 19 | xAxisLegend, 20 | pointData, 21 | yAxisLegend, 22 | xCoordinateForDataPoint, 23 | yCoordinateForDataPoint, 24 | xForWindow, 25 | windowSize, 26 | toolTipLabelFontSize = moderateScale(12), 27 | toolTipHorizontalPadding = horizontalScale(20), 28 | toolTipFadeOutDuration = 4000 29 | }: UseTooltipPropsType) => { 30 | const { fontStyle } = useDefaultFont({ labelSize: toolTipLabelFontSize }); 31 | const userAddedFont = useFont(labelFontFamily, toolTipLabelFontSize); 32 | const font: SkFont | null = labelFontFamily ? userAddedFont : matchFont(fontStyle); 33 | const labelForX = xAxisLegend || 'X'; 34 | const labelForY = yAxisLegend || 'Y'; 35 | const longestFont = 36 | font && 37 | font.measureText(`${labelForX}: ${pointData.x}`).width > 38 | font.measureText(`${labelForY}: ${pointData.y}`).width 39 | ? `${labelForX}: ${pointData.x}` 40 | : `${labelForY}: ${pointData.y}`; 41 | const tooltipWidth = font ? font.measureText(longestFont).width + toolTipHorizontalPadding : 0; 42 | const halfTooltipWidth = tooltipWidth / 2; 43 | const tooltipHeight = 3 * toolTipLabelFontSize; 44 | const tipHeight = verticalScale(10); // The pointed tip of the tooltip 45 | const textPaddingLeft = toolTipHorizontalPadding / 2; 46 | const fontPaddingOffset = toolTipLabelFontSize * 0.2; // 0.2 is magic number is to adjust font padding 47 | const yCordOffsetForText = toolTipLabelFontSize + fontPaddingOffset; // To make sure font does not crop/overlap at top 48 | 49 | // Calculate the coordinates of the vertices of an equilateral triangle 50 | let x1 = xCoordinateForDataPoint.current - tipHeight; 51 | let y1 = yCoordinateForDataPoint.current - tipHeight; 52 | let x2 = xCoordinateForDataPoint.current + tipHeight; 53 | let y2 = yCoordinateForDataPoint.current - tipHeight; 54 | let x3 = xCoordinateForDataPoint.current; 55 | let y3 = yCoordinateForDataPoint.current; 56 | 57 | /* Initial position of tooltip: display on top of the data point without being cropped from 58 | either left or right side */ 59 | let xCordForRoundedRect = xCoordinateForDataPoint.current - halfTooltipWidth; 60 | let yCordForRoundedRect = yCoordinateForDataPoint.current - (tooltipHeight + tipHeight); 61 | let xCordForTopText = xCordForRoundedRect + textPaddingLeft; 62 | let yCordForTopText = yCordForRoundedRect + yCordOffsetForText; 63 | let xCordForBottomText = xCordForTopText; 64 | let yCordForBottomText = yCordForTopText + yCordOffsetForText; 65 | 66 | /* Handle the case where the tooltip might get cropped from top. Redraw and position it below 67 | the data point */ 68 | if (yCoordinateForDataPoint.current - (tooltipHeight + tipHeight) < 0) { 69 | xCordForRoundedRect = xCoordinateForDataPoint.current - halfTooltipWidth; 70 | yCordForRoundedRect = yCoordinateForDataPoint.current + tipHeight; 71 | xCordForTopText = xCordForRoundedRect + textPaddingLeft; 72 | yCordForTopText = yCordForRoundedRect + yCordOffsetForText; 73 | xCordForBottomText = xCordForTopText; 74 | yCordForBottomText = yCordForTopText + yCordOffsetForText; 75 | 76 | x1 = xCoordinateForDataPoint.current; 77 | y1 = yCoordinateForDataPoint.current; 78 | x2 = xCoordinateForDataPoint.current - tipHeight; 79 | y2 = yCoordinateForDataPoint.current + tipHeight; 80 | x3 = xCoordinateForDataPoint.current + tipHeight; 81 | y3 = yCoordinateForDataPoint.current + tipHeight; 82 | } 83 | 84 | if (xCoordinateForDataPoint.current - xForWindow > halfTooltipWidth) { 85 | if (xCoordinateForDataPoint.current - xForWindow + halfTooltipWidth > windowSize.current.x) { 86 | /* Handle the case where the tooltip might get cropped from right side. Redraw and position it on 87 | left side of the data point */ 88 | xCordForRoundedRect = xCoordinateForDataPoint.current - tooltipWidth - tipHeight; 89 | yCordForRoundedRect = yCoordinateForDataPoint.current - tooltipHeight / 2; 90 | xCordForTopText = xCordForRoundedRect + textPaddingLeft; 91 | yCordForTopText = yCordForRoundedRect + yCordOffsetForText; 92 | xCordForBottomText = xCordForTopText; 93 | yCordForBottomText = yCordForTopText + yCordOffsetForText; 94 | 95 | x1 = xCoordinateForDataPoint.current; 96 | y1 = yCoordinateForDataPoint.current; 97 | x2 = xCoordinateForDataPoint.current - tipHeight; 98 | y2 = yCoordinateForDataPoint.current - tipHeight; 99 | x3 = xCoordinateForDataPoint.current - tipHeight; 100 | y3 = yCoordinateForDataPoint.current + tipHeight; 101 | } 102 | } else { 103 | /* Handle the case where the tooltip might get cropped from left side. Redraw and position it on 104 | right side of the data point */ 105 | xCordForRoundedRect = xCoordinateForDataPoint.current + tipHeight; 106 | yCordForRoundedRect = yCoordinateForDataPoint.current - tooltipHeight / 2; 107 | xCordForTopText = xCordForRoundedRect + textPaddingLeft; 108 | yCordForTopText = yCordForRoundedRect + yCordOffsetForText; 109 | xCordForBottomText = xCordForTopText; 110 | yCordForBottomText = yCordForTopText + yCordOffsetForText; 111 | 112 | x1 = xCoordinateForDataPoint.current; 113 | y1 = yCoordinateForDataPoint.current; 114 | x2 = xCoordinateForDataPoint.current + tipHeight; 115 | y2 = yCoordinateForDataPoint.current - tipHeight; 116 | x3 = xCoordinateForDataPoint.current + tipHeight; 117 | y3 = yCoordinateForDataPoint.current + tipHeight; 118 | } 119 | 120 | const path = Skia.Path.Make(); 121 | // Move to the first vertex 122 | path.moveTo(x1, y1); 123 | // Line to the second vertex 124 | path.lineTo(x2, y2); 125 | // Line to the third vertex 126 | path.lineTo(x3, y3); 127 | // Close the path to connect the last and first vertices 128 | path.close(); 129 | 130 | const transformOpacity = useValue(0); 131 | 132 | useEffect(() => { 133 | if (pointData.x !== '0' && pointData.y !== '0') { 134 | runTiming(transformOpacity, { from: 0, to: 1 }, { duration: toolTipFadeOutDuration }); 135 | } 136 | // eslint-disable-next-line react-hooks/exhaustive-deps 137 | }, [pointData]); 138 | 139 | const opacity: SkiaValue = useComputedValue(() => { 140 | return interpolate(transformOpacity.current, [0, 0.6, 1], [1, 1, 0]); 141 | }, [transformOpacity]); 142 | 143 | return { 144 | font, 145 | xCordForRoundedRect, 146 | yCordForRoundedRect, 147 | tooltipWidth, 148 | xCordForTopText, 149 | path, 150 | yCordForTopText, 151 | xCordForBottomText, 152 | yCordForBottomText, 153 | tooltipHeight, 154 | opacity, 155 | labelForX, 156 | labelForY 157 | }; 158 | }; 159 | 160 | export default useTooltip; 161 | -------------------------------------------------------------------------------- /src/components/tooltip/useTooltipUtils.ts: -------------------------------------------------------------------------------- 1 | import { useValue } from '@shopify/react-native-skia'; 2 | import { useRef, useState } from 'react'; 3 | import type { PointDataType, SetWindowSizeArgsType, WindowSizeDataType } from './TooltipTypes'; 4 | import type { NativeScrollEvent } from 'react-native'; 5 | 6 | const useTooltipUtils = () => { 7 | const windowSize = useRef({ 8 | x: 0, 9 | y: 0 10 | }); 11 | const xForWindow = useRef(0); 12 | const xCoordinateForDataPoint = useValue(0); 13 | const yCoordinateForDataPoint = useValue(0); 14 | const [pointData, setPointData] = useState({ 15 | x: '0', 16 | y: '0' 17 | }); 18 | 19 | const setXForWindow = ({ nativeEvent }: { nativeEvent: NativeScrollEvent }) => { 20 | xForWindow.current = nativeEvent.contentOffset.x; 21 | }; 22 | 23 | const setWindowSize = ({ nativeEvent }: SetWindowSizeArgsType) => { 24 | windowSize.current.x = nativeEvent.layout.width; 25 | windowSize.current.y = nativeEvent.layout.height; 26 | }; 27 | 28 | return { 29 | windowSize, 30 | xForWindow, 31 | pointData, 32 | setPointData, 33 | xCoordinateForDataPoint, 34 | yCoordinateForDataPoint, 35 | setXForWindow, 36 | setWindowSize 37 | }; 38 | }; 39 | 40 | export default useTooltipUtils; 41 | -------------------------------------------------------------------------------- /src/constants/Constants.ts: -------------------------------------------------------------------------------- 1 | import { globalMetrics } from '../theme'; 2 | 3 | export const MAX_CANVAS_WIDTH = globalMetrics.isAndroid ? 5948 : 2718; 4 | export const DEFAULT_LABEL_SIZE = 18; 5 | export const LINE_ANIMATION_TIME = 1000; 6 | export const CHART_X_LABEL_HEIGHT_RECTIFIER = 2; 7 | export const X_AXIS_LABEL_WIDTH_RECTIFIER = 15; 8 | export const Y_AXIS_LEGEND_TRUE_VALUE = 2.6; 9 | export const Y_AXIS_LEGEND_FALSE_VALUE = 0.5; 10 | export const Y_AXIS_LABEL_HORIZONTAL_GAP = 10; 11 | export const TOOLTIP_DATA_POINT_CIRCLE_RECTIFIER = 11; 12 | export const TOOLTIP_BORDER_RADIUS_RECTIFIER = 14; 13 | export const BARGRAPH_TOOLTIP_HITSLOP = 10; 14 | export const CHART_BOTTOM_MARGIN = 14; 15 | export const AXIS_POSITION_VALUE = 25; 16 | export const INITIAL_SPACE = 10; 17 | -------------------------------------------------------------------------------- /src/constants/index.ts: -------------------------------------------------------------------------------- 1 | export * from './Constants'; 2 | -------------------------------------------------------------------------------- /src/hooks/index.ts: -------------------------------------------------------------------------------- 1 | export { default as useDefaultFont } from './useDefaultFont'; 2 | -------------------------------------------------------------------------------- /src/hooks/useDefaultFont.ts: -------------------------------------------------------------------------------- 1 | import { listFontFamilies } from '@shopify/react-native-skia'; 2 | import { Platform } from 'react-native'; 3 | 4 | type UseDefaultFontPropsType = { 5 | labelSize: number; 6 | }; 7 | 8 | /** 9 | * The function `useDefaultFont` selects the default font provided with the given fontsize. 10 | * a `fontStyle` object with the selected font family and font size. 11 | * @param {UseDefaultFontPropsType} - - `labelSize`: The size of the label font. 12 | * @returns an object with a property called "fontStyle". 13 | */ 14 | const useDefaultFont = ({ labelSize }: UseDefaultFontPropsType) => { 15 | /** 16 | * Get the default font family from the available font families list. 17 | * @returns {string[]} 18 | */ 19 | const defaultFont = listFontFamilies(); 20 | 21 | /** 22 | * Select the appropriate font family based on the platform. 23 | * On iOS, Android, or any other platform, it defaults to the first font in the list. 24 | * @type {string} 25 | */ 26 | const fontFamily: string = Platform.select({ 27 | ios: defaultFont?.[0], 28 | android: defaultFont?.[0], 29 | default: defaultFont?.[0] 30 | }); 31 | 32 | /** 33 | * Create a fontStyle object with the selected fontFamily and fontSize. 34 | */ 35 | const fontStyle = { 36 | fontFamily, 37 | fontSize: labelSize 38 | }; 39 | 40 | return { fontStyle }; 41 | }; 42 | 43 | export default useDefaultFont; 44 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './components'; 2 | -------------------------------------------------------------------------------- /src/theme/Colors.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | white: '#ffffff', 3 | black: '#000000', 4 | blue: '#05259b', 5 | grey: '#949494', 6 | lightgrey: '#D3D3D3', 7 | cherryRed: '#DE5E69', 8 | red: '#ff0000' 9 | }; 10 | -------------------------------------------------------------------------------- /src/theme/Metrics.tsx: -------------------------------------------------------------------------------- 1 | import { Dimensions, Platform, type ScaledSize } from 'react-native'; 2 | 3 | /** 4 | * Get the width and height of the device screen. 5 | * @returns {ScaledSize} - the width and height of the device screen. 6 | */ 7 | let { width, height }: ScaledSize = Dimensions.get('window'); 8 | 9 | if (width > height) { 10 | [width, height] = [height, width]; 11 | } 12 | 13 | //Guideline sizes are based on standard ~5" screen mobile device 14 | const guidelineBaseWidth: number = 375; 15 | 16 | const guidelineBaseHeight: number = 812; 17 | 18 | /** 19 | * Converts provided width to based on provided guideline size width. 20 | * @param {number} size The screen's width that UI element should cover 21 | * @return {number} The calculated scale depending on current device's screen width. 22 | */ 23 | const horizontalScale = (size: number): number => 24 | (width / guidelineBaseWidth) * size; 25 | 26 | /** 27 | * Converts provided height to based on provided guideline size height. 28 | * @param {number} size The screen's height that UI element should cover 29 | * @return {number} The calculated vertical scale depending on current device's screen height. 30 | */ 31 | const verticalScale = (size: number): number => 32 | (height / guidelineBaseHeight) * size; 33 | 34 | /** 35 | * Converts provided size to based on provided guideline size width. 36 | * @param {number} size - The size of the font you want to scale 37 | * @param {number} [factor=0.5] - The amount of scaling to apply to font sizes. Defaults to 0.5. 38 | * @return {number} The calculated moderate scale depending on current device's screen width. 39 | */ 40 | const moderateScale = (size: number, factor = 0.5): number => 41 | size + (horizontalScale(size) - size) * factor; 42 | 43 | /** 44 | * A type that contains the global metrics for the current device. 45 | * @typedef {Object} GlobalMetricsType - A type that contains the global metrics for the current device. 46 | * @property {boolean} isAndroid - Whether the current device is an Android device. 47 | */ 48 | interface GlobalMetricsType { 49 | isAndroid: boolean; 50 | isIos: boolean; 51 | isPad: boolean; 52 | isTV: boolean; 53 | isWeb: boolean; 54 | } 55 | 56 | /** 57 | * A type that contains the global metrics for the app. 58 | * @type {GlobalMetricsType} 59 | */ 60 | const globalMetrics: GlobalMetricsType = { 61 | isAndroid: Platform.OS === 'android', 62 | isIos: Platform.OS === 'ios', 63 | isPad: Platform.OS === 'ios' && Platform.isPad, 64 | isTV: Platform.isTV, 65 | isWeb: Platform.OS === 'web', 66 | }; 67 | 68 | const screenHeight: number = Dimensions.get('window').height; 69 | const chartWidth: number = Dimensions.get('screen').width; 70 | 71 | export { 72 | globalMetrics, 73 | horizontalScale, 74 | verticalScale, 75 | moderateScale, 76 | width, 77 | height, 78 | screenHeight, 79 | chartWidth, 80 | }; 81 | -------------------------------------------------------------------------------- /src/theme/index.ts: -------------------------------------------------------------------------------- 1 | export { default as Colors } from './Colors'; 2 | export * from './Metrics'; 3 | -------------------------------------------------------------------------------- /src/utils/CommonUtils.ts: -------------------------------------------------------------------------------- 1 | import { SkFont, Skia } from '@shopify/react-native-skia'; 2 | import type { ScaledDataType } from '../components/line-chart/LineChartTypes'; 3 | import { MAX_CANVAS_WIDTH } from '../constants'; 4 | 5 | /** 6 | * Calculate the canvas width for rendering data on a canvas. 7 | * 8 | * @param {number} xAxisLength - The length of the x-axis (optional, defaults to 0). 9 | * @param {number} initialDistance - The initial distance (optional, defaults to 10). 10 | * @param {number} dataLength - The length of the data to be rendered. 11 | * @returns {number} The calculated canvas width. 12 | */ 13 | export function calculateCanvasWidth( 14 | xAxisLength: number = 0, 15 | initialDistance: number = 10, 16 | dataLength: number 17 | ): number { 18 | const calculatedWidth = xAxisLength * dataLength + initialDistance; 19 | return calculatedWidth > MAX_CANVAS_WIDTH ? MAX_CANVAS_WIDTH : calculatedWidth; 20 | } 21 | 22 | /** 23 | * The function calculates the maximum width of a label in a chart using a given font. 24 | * @param {string[]} labels - An array of strings representing the labels in a chart. 25 | * @param {SkFont | null} chartFont - The `chartFont` parameter is of type `SkFont | null`. It 26 | * represents the font used for measuring the width of the labels in the chart. It can either be a 27 | * valid `SkFont` object or `null` if no font is specified. 28 | * @returns the maximum width of the labels in the given array, taking into account the font size 29 | * specified in the chartFont parameter. 30 | */ 31 | export function calculateMaxWidthLabel(labels: string[], chartFont: SkFont | null) { 32 | return labels.reduce((max, item) => { 33 | return Math.max(max, chartFont?.measureText(item).width as number) + 1; 34 | }, 0); 35 | } 36 | 37 | /** 38 | * The function `findMaxNumber` takes an array of numbers and returns the maximum number in the array. 39 | * @param {number[]} data - An array of numbers 40 | * @returns the maximum number from the given array of numbers. 41 | */ 42 | export function findMaxNumber(data: number[]) { 43 | return data.reduce((prev: number, cur: number) => Math.max(prev, Number(cur)), -Infinity); 44 | } 45 | 46 | /** 47 | * The function generates a line path using scaled data points. 48 | * @param {ScaledDataType} scaledData - The `scaledData` parameter is an array of objects representing 49 | * scaled data points. Each object in the array has two properties: `x` and `y`, which represent the x 50 | * and y coordinates of a data point. 51 | * @returns a Skia Path. 52 | */ 53 | export function generateLinePath(scaledData: ScaledDataType) { 54 | const newPath = Skia.Path.Make(); 55 | 56 | for (let i = 0; i < scaledData.length; i++) { 57 | const point = scaledData[i]; 58 | 59 | if (i === 0) { 60 | newPath.moveTo(point.x, point.y); 61 | } else { 62 | const prev = scaledData[i - 1]; 63 | const cp1x = (2 * prev.x + point.x) / 3; 64 | const cp1y = (2 * prev.y + point.y) / 3; 65 | const cp2x = (prev.x + 2 * point.x) / 3; 66 | const cp2y = (prev.y + 2 * point.y) / 3; 67 | 68 | newPath.cubicTo(cp1x, cp1y, cp2x, cp2y, point.x, point.y); 69 | } 70 | } 71 | 72 | return newPath; 73 | } 74 | -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | export * from './CommonUtils'; 2 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "declaration": true, 5 | "esModuleInterop": true, 6 | "allowUnreachableCode": false, 7 | "allowUnusedLabels": false, 8 | "jsx": "react", 9 | "lib": ["ESNext"], 10 | "module": "ESNext", 11 | "importsNotUsedAsValues": "error", 12 | "forceConsistentCasingInFileNames": true, 13 | "moduleResolution": "Node", 14 | "noFallthroughCasesInSwitch": true, 15 | "noImplicitReturns": true, 16 | "noImplicitUseStrict": false, 17 | "noStrictGenericChecks": false, 18 | "noUnusedLocals": true, 19 | "noUnusedParameters": true, 20 | "resolveJsonModule": true, 21 | "noEmitOnError": true, 22 | "outDir": "./lib", 23 | "skipLibCheck": true, 24 | "sourceMap": true, 25 | "strict": true, 26 | "target": "ES2018" 27 | }, 28 | "exclude": ["example/node_modules/**", "node_modules/**", "**/__tests__/*"], 29 | "include": ["src"] 30 | } 31 | --------------------------------------------------------------------------------