├── .circleci └── config.yml ├── .editorconfig ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── bug.yaml │ ├── config.yaml │ └── feature.yaml ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── codeql-analysis.yml ├── .gitignore ├── .husky ├── .npmignore ├── commit-msg └── pre-commit ├── .yarnrc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── assets └── drawingExample.gif ├── babel.config.js ├── example ├── app.json ├── babel.config.js ├── index.js ├── metro.config.js ├── package.json ├── src │ ├── App.tsx │ ├── components │ │ ├── Button.tsx │ │ └── index.ts │ └── screens │ │ ├── ExampleSelection.tsx │ │ ├── ExtrasExample.tsx │ │ ├── Home.tsx │ │ ├── MoreComplexExample.tsx │ │ ├── SimpleExample.tsx │ │ ├── brushPreview │ │ ├── BrushPreviewExample.tsx │ │ └── data.ts │ │ ├── brushProperties │ │ ├── BrushPropertiesExample.tsx │ │ └── data.ts │ │ ├── canvas │ │ ├── CanvasExample.tsx │ │ └── data.ts │ │ ├── canvasControls │ │ ├── CanvasControlsExample.tsx │ │ └── data.ts │ │ ├── colorPicker │ │ ├── ColorPickerExample.tsx │ │ └── data.ts │ │ └── index.ts ├── tsconfig.json ├── webpack.config.js └── yarn.lock ├── lerna.json ├── package.json ├── packages ├── react-native-draw-extras │ ├── CHANGELOG.md │ ├── README.md │ ├── package.json │ ├── src │ │ ├── BrushPreview.tsx │ │ ├── Button.tsx │ │ ├── CanvasControls.tsx │ │ ├── brushProperties │ │ │ ├── BrushProperties.tsx │ │ │ └── colorPicker │ │ │ │ ├── ColorButton.tsx │ │ │ │ └── ColorPicker.tsx │ │ ├── constants.ts │ │ ├── icons │ │ │ ├── Brush.tsx │ │ │ ├── Delete.tsx │ │ │ ├── Eraser.tsx │ │ │ ├── Palette.tsx │ │ │ ├── Undo.tsx │ │ │ └── index.ts │ │ ├── index.tsx │ │ ├── types.ts │ │ └── utils.ts │ └── tsconfig.json └── react-native-draw │ ├── CHANGELOG.md │ ├── README.md │ ├── package.json │ ├── src │ ├── Canvas.tsx │ ├── constants.ts │ ├── index.tsx │ ├── renderer │ │ ├── RendererHelper.tsx │ │ └── SVGRenderer.tsx │ ├── types.ts │ └── utils.ts │ └── tsconfig.json ├── scripts └── bootstrap.js ├── tsconfig.json └── yarn.lock /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | executors: 4 | default: 5 | docker: 6 | - image: circleci/node:12 7 | working_directory: ~/project 8 | 9 | commands: 10 | attach_project: 11 | steps: 12 | - attach_workspace: 13 | at: ~/project 14 | 15 | jobs: 16 | install-dependencies: 17 | executor: default 18 | steps: 19 | - checkout 20 | - attach_project 21 | - restore_cache: 22 | keys: 23 | - dependencies-{{ checksum "package.json" }} 24 | - dependencies- 25 | - restore_cache: 26 | keys: 27 | - dependencies-example-{{ checksum "example/package.json" }} 28 | - dependencies-example- 29 | - run: 30 | name: Install dependencies 31 | command: | 32 | yarn install --cwd example --frozen-lockfile 33 | yarn install --frozen-lockfile 34 | - save_cache: 35 | key: dependencies-{{ checksum "package.json" }} 36 | paths: node_modules 37 | - save_cache: 38 | key: dependencies-example-{{ checksum "example/package.json" }} 39 | paths: example/node_modules 40 | - persist_to_workspace: 41 | root: . 42 | paths: . 43 | 44 | lint: 45 | executor: default 46 | steps: 47 | - attach_project 48 | - run: 49 | name: Lint files 50 | command: | 51 | yarn lint 52 | 53 | typescript: 54 | executor: default 55 | steps: 56 | - attach_project 57 | - run: 58 | name: Typecheck files 59 | command: | 60 | yarn typescript 61 | 62 | build-packages: 63 | executor: default 64 | steps: 65 | - attach_project 66 | - run: 67 | name: Build packages in the monorepo 68 | command: yarn lerna run prepare 69 | - run: 70 | name: Verify built type definitions are correct 71 | command: yarn typescript 72 | 73 | workflows: 74 | build-and-test: 75 | jobs: 76 | - install-dependencies 77 | - lint: 78 | requires: 79 | - install-dependencies 80 | - typescript: 81 | requires: 82 | - install-dependencies 83 | - build-packages: 84 | requires: 85 | - install-dependencies 86 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | indent_style = space 10 | indent_size = 2 11 | 12 | end_of_line = lf 13 | charset = utf-8 14 | trim_trailing_whitespace = true 15 | insert_final_newline = true 16 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | # specific for windows script files 3 | *.bat text eol=crlf -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug.yaml: -------------------------------------------------------------------------------- 1 | name: 🐛 Bug Report 2 | description: Report a reproducible bug or regression 3 | labels: [bug, needs triage] 4 | body: 5 | - type: checkboxes 6 | attributes: 7 | label: On what kind of device are you using this library? 8 | description: You may select more than one. 9 | options: 10 | - label: Android 11 | - label: iOS 12 | - label: Web 13 | - type: textarea 14 | attributes: 15 | label: Environment 16 | description: | 17 | examples: 18 | - **OS**: Ubuntu 20.04 19 | - **react-native**: 0.67.2 20 | - **@benjeau/react-native-draw**: 0.6.0 21 | value: | 22 | - OS: 23 | - react-native: 24 | - @benjeau/react-native-draw: 25 | render: markdown 26 | validations: 27 | required: true 28 | - type: textarea 29 | attributes: 30 | label: Current Behavior 31 | description: A concise description of what you're experiencing. 32 | validations: 33 | required: true 34 | - type: textarea 35 | attributes: 36 | label: Expected Behavior 37 | description: A concise description of what you expected to happen. 38 | validations: 39 | required: true 40 | - type: textarea 41 | attributes: 42 | label: Steps To Reproduce 43 | description: Steps to reproduce the behavior. 44 | placeholder: | 45 | 1. In this environment... 46 | 2. With this config... 47 | 3. Run '...' 48 | 4. See error... 49 | validations: 50 | required: true 51 | - type: textarea 52 | attributes: 53 | label: Anything else? 54 | description: | 55 | Links? References? Anything that will give us more context about the issue you are encountering! 56 | 57 | Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yaml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature.yaml: -------------------------------------------------------------------------------- 1 | name: 🚀 Feature Request 2 | description: I have a suggestion (and may want to implement it 🙂)! 3 | labels: [enhancement, needs triage] 4 | body: 5 | - type: textarea 6 | attributes: 7 | label: Is your feature request related to a problem? 8 | description: A clear and concise description of what the problem is. Ex. I have an issue when [...] 9 | - type: textarea 10 | attributes: 11 | label: Desired solution (feature) 12 | description: A clear and concise description of what you want to happen. Add any considered drawbacks. 13 | validations: 14 | required: true 15 | - type: textarea 16 | attributes: 17 | label: Alternatives considered 18 | description: A clear and concise description of any alternative solutions or features you've considered. 19 | - type: textarea 20 | attributes: 21 | label: Anything else? 22 | description: | 23 | Links? References? Anything that will give us more context about the issue you are encountering! 24 | 25 | Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Changes 2 | 3 | 4 | 5 | ## Related Issues 6 | 7 | 8 | 9 | ## Screenshots (optional) 10 | 11 | 12 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ master ] 20 | schedule: 21 | - cron: '32 2 * * 5' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'javascript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 37 | # Learn more: 38 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 39 | 40 | steps: 41 | - name: Checkout repository 42 | uses: actions/checkout@v2 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # XDE 6 | .expo/ 7 | 8 | # VSCode 9 | .vscode/ 10 | jsconfig.json 11 | 12 | # Xcode 13 | # 14 | build/ 15 | *.pbxuser 16 | !default.pbxuser 17 | *.mode1v3 18 | !default.mode1v3 19 | *.mode2v3 20 | !default.mode2v3 21 | *.perspectivev3 22 | !default.perspectivev3 23 | xcuserdata 24 | *.xccheckout 25 | *.moved-aside 26 | DerivedData 27 | *.hmap 28 | *.ipa 29 | *.xcuserstate 30 | project.xcworkspace 31 | 32 | # Android/IJ 33 | # 34 | .classpath 35 | .cxx 36 | .gradle 37 | .idea 38 | .project 39 | .settings 40 | local.properties 41 | android.iml 42 | 43 | # Cocoapods 44 | # 45 | example/ios/Pods 46 | 47 | # node.js 48 | # 49 | node_modules/ 50 | npm-debug.log 51 | yarn-debug.log 52 | yarn-error.log 53 | 54 | # BUCK 55 | buck-out/ 56 | \.buckd/ 57 | android/app/libs 58 | android/keystores/debug.keystore 59 | 60 | # Expo 61 | .expo/* 62 | 63 | # generated by bob 64 | lib/ 65 | -------------------------------------------------------------------------------- /.husky/.npmignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn commitlint -E HUSKY_GIT_PARAMS 5 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn lint && yarn typescript 5 | -------------------------------------------------------------------------------- /.yarnrc: -------------------------------------------------------------------------------- 1 | # Override Yarn command so we can automatically setup the repo on running `yarn` 2 | 3 | yarn-path "scripts/bootstrap.js" 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. 4 | 5 | ## Development workflow 6 | 7 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package: 8 | 9 | ```sh 10 | yarn 11 | ``` 12 | 13 | > While it's possible to use [`npm`](https://github.com/npm/cli), the tooling is built around [`yarn`](https://classic.yarnpkg.com/), so you'll have an easier time if you use `yarn` for development. 14 | 15 | While developing, you can run the [example app](/example/) to test your changes. Any changes you make in your library's JavaScript code will be reflected in the example app without a rebuild. If you change any native code, then you'll need to rebuild the example app. 16 | 17 | To start the packager: 18 | 19 | ```sh 20 | yarn example start 21 | ``` 22 | 23 | To run the example app on Android: 24 | 25 | ```sh 26 | yarn example android 27 | ``` 28 | 29 | To run the example app on iOS: 30 | 31 | ```sh 32 | yarn example ios 33 | ``` 34 | 35 | To run the example app on Web: 36 | 37 | ```sh 38 | yarn example web 39 | ``` 40 | 41 | Make sure your code passes TypeScript and ESLint. Run the following to verify: 42 | 43 | ```sh 44 | yarn typescript 45 | yarn lint 46 | ``` 47 | 48 | To fix formatting errors, run the following: 49 | 50 | ```sh 51 | yarn lint --fix 52 | ``` 53 | 54 | Remember to add tests for your change if possible. Run the unit tests by: 55 | 56 | ```sh 57 | yarn test 58 | ``` 59 | 60 | ### Commit message convention 61 | 62 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: 63 | 64 | - `fix`: bug fixes, e.g. fix crash due to deprecated method. 65 | - `feat`: new features, e.g. add new method to the module. 66 | - `refactor`: code refactor, e.g. migrate from class components to hooks. 67 | - `docs`: changes into documentation, e.g. add usage example for the module.. 68 | - `test`: adding or updating tests, e.g. add integration tests using detox. 69 | - `chore`: tooling changes, e.g. change CI config. 70 | 71 | Our pre-commit hooks verify that your commit message matches this format when committing. 72 | 73 | ### Linting and tests 74 | 75 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) 76 | 77 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing. 78 | 79 | Our pre-commit hooks verify that the linter and tests pass when committing. 80 | 81 | ### Publishing to npm 82 | 83 | We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc. 84 | 85 | To publish new versions, run the following: 86 | 87 | ```sh 88 | yarn release 89 | ``` 90 | 91 | ### Scripts 92 | 93 | The `package.json` file contains various scripts for common tasks: 94 | 95 | - `yarn bootstrap`: setup project by installing all dependencies and pods. 96 | - `yarn typescript`: type-check files with TypeScript. 97 | - `yarn lint`: lint files with ESLint. 98 | - `yarn test`: run unit tests with Jest. 99 | - `yarn example start`: start the Metro server for the example app. 100 | - `yarn example android`: run the example app on Android. 101 | - `yarn example ios`: run the example app on iOS. 102 | 103 | ### Sending a pull request 104 | 105 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github). 106 | 107 | When you're sending a pull request: 108 | 109 | - Prefer small pull requests focused on one change. 110 | - Verify that linters and tests are passing. 111 | - Review the documentation to make sure it looks good. 112 | - Follow the pull request template when opening a pull request. 113 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 114 | 115 | ## Code of Conduct 116 | 117 | ### Our Pledge 118 | 119 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 120 | 121 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 122 | 123 | ### Our Standards 124 | 125 | Examples of behavior that contributes to a positive environment for our community include: 126 | 127 | - Demonstrating empathy and kindness toward other people 128 | - Being respectful of differing opinions, viewpoints, and experiences 129 | - Giving and gracefully accepting constructive feedback 130 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 131 | - Focusing on what is best not just for us as individuals, but for the overall community 132 | 133 | Examples of unacceptable behavior include: 134 | 135 | - The use of sexualized language or imagery, and sexual attention or 136 | advances of any kind 137 | - Trolling, insulting or derogatory comments, and personal or political attacks 138 | - Public or private harassment 139 | - Publishing others' private information, such as a physical or email 140 | address, without their explicit permission 141 | - Other conduct which could reasonably be considered inappropriate in a 142 | professional setting 143 | 144 | ### Enforcement Responsibilities 145 | 146 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 147 | 148 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 149 | 150 | ### Scope 151 | 152 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 153 | 154 | ### Enforcement 155 | 156 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. 157 | 158 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 159 | 160 | ### Enforcement Guidelines 161 | 162 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 163 | 164 | #### 1. Correction 165 | 166 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 167 | 168 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 169 | 170 | #### 2. Warning 171 | 172 | **Community Impact**: A violation through a single incident or series of actions. 173 | 174 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 175 | 176 | #### 3. Temporary Ban 177 | 178 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 179 | 180 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 181 | 182 | #### 4. Permanent Ban 183 | 184 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 185 | 186 | **Consequence**: A permanent ban from any sort of public interaction within the community. 187 | 188 | ### Attribution 189 | 190 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 191 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 192 | 193 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 194 | 195 | [homepage]: https://www.contributor-covenant.org 196 | 197 | For answers to common questions about this code of conduct, see the FAQ at 198 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 199 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Benoit Jeaurond 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ./packages/react-native-draw/README.md -------------------------------------------------------------------------------- /assets/drawingExample.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BenJeau/react-native-draw/13ff23ff0efebc63f1a2e0c6578cf1beb5ed84bf/assets/drawingExample.gif -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@benjeau/react-native-draw-example", 3 | "displayName": "ReactNativeDraw Example", 4 | "expo": { 5 | "userInterfaceStyle": "automatic", 6 | "name": "@benjeau/react-native-draw-example", 7 | "slug": "benjeau-react-native-draw-example", 8 | "description": "Example app for @benjeau/react-native-draw", 9 | "privacy": "public", 10 | "version": "1.0.0", 11 | "platforms": ["ios", "android", "web"], 12 | "ios": { 13 | "userInterfaceStyle": "automatic", 14 | "supportsTablet": true 15 | }, 16 | "android": { 17 | "userInterfaceStyle": "automatic" 18 | }, 19 | "assetBundlePatterns": ["**/*"] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /example/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = function (api) { 2 | api.cache(true); 3 | 4 | return { 5 | presets: ['babel-preset-expo'], 6 | }; 7 | }; 8 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | import { registerRootComponent } from 'expo'; 2 | 3 | import App from './src/App'; 4 | 5 | // registerRootComponent calls AppRegistry.registerComponent('main', () => App); 6 | // It also ensures that whether you load the app in the Expo client or in a native build, 7 | // the environment is set up appropriately 8 | registerRootComponent(App); 9 | -------------------------------------------------------------------------------- /example/metro.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const fs = require('fs'); 3 | const exclusionList = require('metro-config/src/defaults/exclusionList'); 4 | const escape = require('escape-string-regexp'); 5 | const { getDefaultConfig } = require('@expo/metro-config'); 6 | 7 | const root = path.resolve(__dirname, '..'); 8 | const packages = path.resolve(root, 'packages'); 9 | 10 | const defaultConfig = getDefaultConfig(__dirname); 11 | 12 | // List all packages under `packages/` 13 | const workspaces = fs 14 | .readdirSync(packages) 15 | .map((p) => path.join(packages, p)) 16 | .filter( 17 | (p) => 18 | fs.statSync(p).isDirectory() && 19 | fs.existsSync(path.join(p, 'package.json')) 20 | ); 21 | 22 | // Get the list of dependencies for all packages in the monorepo 23 | const modules = [] 24 | .concat( 25 | ...workspaces.map((it) => { 26 | const pak = JSON.parse( 27 | fs.readFileSync(path.join(it, 'package.json'), 'utf8') 28 | ); 29 | 30 | // We need to make sure that only one version is loaded for peerDependencies 31 | // So we exclude them at the root, and alias them to the versions in example's node_modules 32 | return pak.peerDependencies ? Object.keys(pak.peerDependencies) : []; 33 | }) 34 | ) 35 | .sort() 36 | .filter( 37 | (m, i, self) => 38 | // Remove duplicates and package names of the packages in the monorepo 39 | self.lastIndexOf(m) === i && !m.startsWith('@react-navigation/') 40 | ); 41 | 42 | module.exports = { 43 | ...defaultConfig, 44 | 45 | projectRoot: __dirname, 46 | 47 | // We need to watch the root of the monorepo 48 | // This lets Metro find the monorepo packages automatically using haste 49 | // This also lets us import modules from monorepo root 50 | watchFolders: [root], 51 | 52 | resolver: { 53 | ...defaultConfig.resolver, 54 | 55 | // We need to exclude the peerDependencies we've collected in packages' node_modules 56 | blacklistRE: exclusionList( 57 | [].concat( 58 | ...workspaces.map((it) => 59 | modules.map( 60 | (m) => 61 | new RegExp(`^${escape(path.join(it, 'node_modules', m))}\\/.*$`) 62 | ) 63 | ) 64 | ) 65 | ), 66 | 67 | // When we import a package from the monorepo, metro won't be able to find their deps 68 | // We need to specify them in `extraNodeModules` to tell metro where to find them 69 | extraNodeModules: modules.reduce((acc, name) => { 70 | acc[name] = path.join(root, 'node_modules', name); 71 | return acc; 72 | }, {}), 73 | }, 74 | 75 | // transformer: { 76 | // getTransformOptions: async () => ({ 77 | // transform: { 78 | // experimentalImportSupport: false, 79 | // inlineRequires: true, 80 | // }, 81 | // }), 82 | // }, 83 | }; 84 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@benjeau/react-native-draw-example", 3 | "description": "Example app for @benjeau/react-native-draw", 4 | "version": "0.0.1", 5 | "private": true, 6 | "main": "index", 7 | "scripts": { 8 | "android": "expo start --android", 9 | "ios": "expo start --ios", 10 | "web": "expo start --web", 11 | "start": "expo start", 12 | "test": "jest" 13 | }, 14 | "dependencies": { 15 | "@react-native-community/slider": "4.1.12", 16 | "@react-navigation/native": "^6.0.6", 17 | "@react-navigation/native-stack": "^6.2.5", 18 | "expo": "^44.0.6", 19 | "expo-splash-screen": "~0.14.1", 20 | "react": "17.0.1", 21 | "react-dom": "^17.0.2", 22 | "react-native": "0.64.3", 23 | "react-native-gesture-handler": "~2.1.0", 24 | "react-native-safe-area-context": "3.3.2", 25 | "react-native-screens": "~3.10.1", 26 | "react-native-svg": "12.1.1", 27 | "react-native-unimodules": "~0.15.0", 28 | "react-native-web": "0.17.1" 29 | }, 30 | "devDependencies": { 31 | "@babel/core": "^7.12.9", 32 | "@babel/runtime": "^7.9.6", 33 | "@types/react-native": "0.64.2", 34 | "babel-loader": "^8.2.3", 35 | "babel-plugin-module-resolver": "^4.0.0", 36 | "babel-preset-expo": "8.5.1", 37 | "expo-cli": "^4.0.13", 38 | "jest": "^27.5.0" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { StatusBar, useColorScheme } from 'react-native'; 3 | import { 4 | DarkTheme, 5 | DefaultTheme, 6 | NavigationContainer, 7 | } from '@react-navigation/native'; 8 | import { createNativeStackNavigator } from '@react-navigation/native-stack'; 9 | import type { CanvasProps } from '@benjeau/react-native-draw'; 10 | import type { 11 | BrushPreviewProps, 12 | BrushPropertiesProps, 13 | CanvasControlsProps, 14 | ColorPickerProps, 15 | } from '@benjeau/react-native-draw-extras'; 16 | 17 | import { 18 | CanvasExample, 19 | Home, 20 | ExampleSelection, 21 | ExtrasExample, 22 | MoreComplexExample, 23 | SimpleExample, 24 | BrushPreviewExample, 25 | BrushPropertiesExample, 26 | CanvasControlsExample, 27 | ColorPickerExample, 28 | } from './screens'; 29 | 30 | export type RootStackParamList = { 31 | Home: undefined; 32 | CanvasExample: CanvasProps; 33 | BrushPreviewExample: BrushPreviewProps; 34 | BrushPropertiesExample: BrushPropertiesProps; 35 | CanvasControlsExample: CanvasControlsProps; 36 | ColorPickerExample: ColorPickerProps; 37 | ExampleSelection: { 38 | type: 39 | | 'canvas' 40 | | 'brushPreview' 41 | | 'brushProperties' 42 | | 'canvasControls' 43 | | 'colorPicker'; 44 | title: string; 45 | }; 46 | SimpleExample: undefined; 47 | MoreComplexExample: undefined; 48 | ExtrasExample: undefined; 49 | }; 50 | 51 | const Stack = createNativeStackNavigator(); 52 | 53 | export default () => { 54 | const colorScheme = useColorScheme(); 55 | 56 | return ( 57 | <> 58 | 63 | 66 | 67 | 72 | 77 | 82 | 87 | 92 | 97 | 102 | 107 | 112 | ({ title })} 120 | /> 121 | 122 | 123 | 124 | ); 125 | }; 126 | -------------------------------------------------------------------------------- /example/src/components/Button.tsx: -------------------------------------------------------------------------------- 1 | import { useTheme } from '@react-navigation/native'; 2 | import React from 'react'; 3 | import { Pressable, View, Text, StyleSheet, Platform } from 'react-native'; 4 | 5 | interface ButtonProps { 6 | onPress: () => void; 7 | } 8 | 9 | const Button: React.FC = ({ onPress, children }) => { 10 | const theme = useTheme(); 11 | 12 | return ( 13 | 16 | ({ 18 | ...(Platform.OS === 'ios' 19 | ? { 20 | backgroundColor: pressed 21 | ? theme.colors.border 22 | : theme.colors.card, 23 | borderWidth: StyleSheet.hairlineWidth, 24 | borderColor: theme.colors.border, 25 | } 26 | : {}), 27 | ...styles.button, 28 | })} 29 | android_ripple={{ color: theme.colors.text }} 30 | onPress={onPress} 31 | > 32 | 40 | {children} 41 | 42 | 43 | 44 | ); 45 | }; 46 | 47 | const styles = StyleSheet.create({ 48 | buttonContainer: { 49 | overflow: 'hidden', 50 | borderRadius: 5, 51 | elevation: 5, 52 | marginBottom: 10, 53 | }, 54 | button: { 55 | padding: 10, 56 | borderRadius: 5, 57 | }, 58 | buttonText: { 59 | lineHeight: 20, 60 | }, 61 | }); 62 | 63 | export default Button; 64 | -------------------------------------------------------------------------------- /example/src/components/index.ts: -------------------------------------------------------------------------------- 1 | export { default as Button } from './Button'; 2 | -------------------------------------------------------------------------------- /example/src/screens/ExampleSelection.tsx: -------------------------------------------------------------------------------- 1 | import React, { useMemo } from 'react'; 2 | import { Text, View, FlatList, StyleSheet } from 'react-native'; 3 | import type { NativeStackScreenProps } from '@react-navigation/native-stack'; 4 | import { useTheme } from '@react-navigation/native'; 5 | 6 | import canvasData from './canvas/data'; 7 | import brushPreviewsData from './brushPreview/data'; 8 | import brushPropertiesData from './brushProperties/data'; 9 | import canvasControlsData from './canvasControls/data'; 10 | import colorPickerData from './colorPicker/data'; 11 | 12 | import type { RootStackParamList } from '../App'; 13 | import { Button } from '../components'; 14 | 15 | type ExampleSelectionProps = NativeStackScreenProps< 16 | RootStackParamList, 17 | 'ExampleSelection' 18 | >; 19 | 20 | const ExampleSelection: React.FC = ({ 21 | route, 22 | navigation, 23 | }) => { 24 | const theme = useTheme(); 25 | 26 | const data = useMemo(() => { 27 | switch (route.params.type) { 28 | case 'canvas': 29 | return canvasData; 30 | case 'brushPreview': 31 | return brushPreviewsData; 32 | case 'brushProperties': 33 | return brushPropertiesData; 34 | case 'canvasControls': 35 | return canvasControlsData; 36 | case 'colorPicker': 37 | return colorPickerData; 38 | default: 39 | return []; 40 | } 41 | }, [route.params]); 42 | 43 | const screenToNavigate = useMemo(() => { 44 | switch (route.params.type) { 45 | case 'canvas': 46 | return 'CanvasExample'; 47 | case 'brushPreview': 48 | return 'BrushPreviewExample'; 49 | case 'brushProperties': 50 | return 'BrushPropertiesExample'; 51 | case 'canvasControls': 52 | return 'CanvasControlsExample'; 53 | case 'colorPicker': 54 | return 'ColorPickerExample'; 55 | default: 56 | return 'CanvasExample'; 57 | } 58 | }, [route.params]); 59 | 60 | return ( 61 | 66 | Various examples of the component with its different props 67 | 68 | } 69 | renderItem={({ item }) => ( 70 | 71 | {!!item.name && ( 72 | 73 | {item.name} 74 | 75 | )} 76 | {item.data.map(({ description, props }, key) => ( 77 | 86 | ))} 87 | 88 | )} 89 | keyExtractor={(_, index) => index.toString()} 90 | contentContainerStyle={styles.listContainer} 91 | /> 92 | ); 93 | }; 94 | 95 | const styles = StyleSheet.create({ 96 | listContainer: { 97 | padding: 20, 98 | }, 99 | sectionTitle: { 100 | fontSize: 18, 101 | marginBottom: 10, 102 | marginTop: 10, 103 | }, 104 | headerText: { 105 | marginBottom: 20, 106 | }, 107 | }); 108 | 109 | export default ExampleSelection; 110 | -------------------------------------------------------------------------------- /example/src/screens/ExtrasExample.tsx: -------------------------------------------------------------------------------- 1 | import React, { useRef, useState } from 'react'; 2 | import { Animated, StyleSheet, View } from 'react-native'; 3 | import { Canvas, CanvasRef, DrawingTool } from '@benjeau/react-native-draw'; 4 | import { 5 | BrushProperties, 6 | CanvasControls, 7 | DEFAULT_COLORS, 8 | } from '@benjeau/react-native-draw-extras'; 9 | import { useTheme } from '@react-navigation/native'; 10 | 11 | export default () => { 12 | const theme = useTheme(); 13 | 14 | const canvasRef = useRef(null); 15 | 16 | const [color, setColor] = useState(DEFAULT_COLORS[0][0][0]); 17 | const [thickness, setThickness] = useState(5); 18 | const [opacity, setOpacity] = useState(1); 19 | const [tool, setTool] = useState(DrawingTool.Brush); 20 | const [visibleBrushProperties, setVisibleBrushProperties] = useState(false); 21 | 22 | const handleUndo = () => { 23 | canvasRef.current?.undo(); 24 | }; 25 | 26 | const handleClear = () => { 27 | canvasRef.current?.clear(); 28 | }; 29 | 30 | const handleToggleEraser = () => { 31 | setTool((prev) => 32 | prev === DrawingTool.Brush ? DrawingTool.Eraser : DrawingTool.Brush 33 | ); 34 | }; 35 | 36 | const [overlayOpacity] = useState(new Animated.Value(0)); 37 | const handleToggleBrushProperties = () => { 38 | if (!visibleBrushProperties) { 39 | setVisibleBrushProperties(true); 40 | 41 | Animated.timing(overlayOpacity, { 42 | toValue: 1, 43 | duration: 200, 44 | useNativeDriver: true, 45 | }).start(); 46 | } else { 47 | Animated.timing(overlayOpacity, { 48 | toValue: 0, 49 | duration: 200, 50 | useNativeDriver: true, 51 | }).start(() => { 52 | setVisibleBrushProperties(false); 53 | }); 54 | } 55 | }; 56 | 57 | return ( 58 | <> 59 | 71 | 72 | 82 | {visibleBrushProperties && ( 83 | 107 | )} 108 | 109 | 110 | ); 111 | }; 112 | -------------------------------------------------------------------------------- /example/src/screens/Home.tsx: -------------------------------------------------------------------------------- 1 | import { useTheme } from '@react-navigation/native'; 2 | import type { NativeStackScreenProps } from '@react-navigation/native-stack'; 3 | import React from 'react'; 4 | import { 5 | ScrollView, 6 | StyleSheet, 7 | Text, 8 | Linking, 9 | TouchableOpacity, 10 | View, 11 | } from 'react-native'; 12 | 13 | import type { RootStackParamList } from '../App'; 14 | import { Button } from '../components'; 15 | 16 | type HomeProps = NativeStackScreenProps; 17 | 18 | const Home: React.FC = ({ navigation }) => { 19 | const theme = useTheme(); 20 | 21 | return ( 22 | 28 | 29 | Various collection of examples, feel free to explore them 30 | 31 | 32 | 33 | Drawing Examples 34 | 35 | 36 | 39 | 42 | 45 | 46 | 47 | Individual Component Examples 48 | 49 | 59 | 69 | 79 | 89 | 99 | 100 | 101 | 102 | 108 | Made with ♥️ by 109 | 110 | Linking.openURL('https://github.com/BenJeau')} 112 | > 113 | @BenJeau 114 | 115 | 116 | 117 | 118 | 125 | Open source and available on 126 | 127 | 129 | Linking.openURL('https://github.com/BenJeau/react-native-draw') 130 | } 131 | > 132 | 133 | GitHub 134 | 135 | 136 | 137 | 138 | 139 | ); 140 | }; 141 | 142 | const styles = StyleSheet.create({ 143 | container: { 144 | padding: 20, 145 | }, 146 | footerContainer: { 147 | alignItems: 'center', 148 | justifyContent: 'center', 149 | marginTop: 20, 150 | }, 151 | footerTop: { 152 | flexDirection: 'row', 153 | }, 154 | footerBottom: { 155 | flexDirection: 'row', 156 | marginTop: 5, 157 | }, 158 | title: { marginVertical: 10, fontSize: 18 }, 159 | description: { marginBottom: 10 }, 160 | }); 161 | 162 | export default Home; 163 | -------------------------------------------------------------------------------- /example/src/screens/MoreComplexExample.tsx: -------------------------------------------------------------------------------- 1 | import React, { useRef } from 'react'; 2 | import { Button } from 'react-native'; 3 | import { Canvas, CanvasRef } from '@benjeau/react-native-draw'; 4 | 5 | export default () => { 6 | const canvasRef = useRef(null); 7 | 8 | const handleUndo = () => { 9 | canvasRef.current?.undo(); 10 | }; 11 | 12 | const handleClear = () => { 13 | canvasRef.current?.clear(); 14 | }; 15 | 16 | return ( 17 | <> 18 | 26 | 91 | )} 92 | {onUndo && ( 93 | 94 | 101 | 102 | )} 103 | 104 | 105 | 111 | 112 | 113 | {onToggleEraser && ( 114 | 125 | )} 126 | {onToggleBrushProperties && color && ( 127 | 128 | 135 | 136 | )} 137 | 138 | 139 | 140 | ); 141 | 142 | const styles = StyleSheet.create({ 143 | container: { 144 | height: 80, 145 | width: '100%', 146 | justifyContent: 'center', 147 | }, 148 | content: { 149 | flexDirection: 'row', 150 | alignItems: 'center', 151 | justifyContent: 'space-between', 152 | marginHorizontal: 15, 153 | }, 154 | buttonsContainer: { 155 | flexDirection: 'row', 156 | justifyContent: 'space-between', 157 | }, 158 | endButton: { 159 | marginLeft: 10, 160 | }, 161 | }); 162 | 163 | export default CanvasControls; 164 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/brushProperties/BrushProperties.tsx: -------------------------------------------------------------------------------- 1 | import React, { forwardRef, useImperativeHandle, useMemo } from 'react'; 2 | import { Animated, StyleProp, StyleSheet, View, ViewStyle } from 'react-native'; 3 | import Slider from '@react-native-community/slider'; 4 | 5 | import { 6 | DEFAULT_COLORS, 7 | DEFAULT_OPACITY, 8 | DEFAULT_OPACITY_STEP, 9 | DEFAULT_SLIDER_COLOR, 10 | DEFAULT_THICKNESS, 11 | DEFAULT_THICKNESS_MAX, 12 | DEFAULT_THICKNESS_MIN, 13 | DEFAULT_THICKNESS_STEP, 14 | SLIDERS_HEIGHT, 15 | } from '../constants'; 16 | import ColorPicker, { ColorPickerProps } from './colorPicker/ColorPicker'; 17 | import { colorButtonSize } from './colorPicker/ColorButton'; 18 | 19 | export interface BrushPropertiesProps extends ColorPickerProps { 20 | /** 21 | * Thickness of the brush strokes 22 | * @default DEFAULT_THICKNESS 23 | */ 24 | thickness?: number; 25 | 26 | /** 27 | * Opacity of the brush strokes 28 | * @default DEFAULT_OPACITY 29 | */ 30 | opacity?: number; 31 | 32 | /** 33 | * Callback when brush size is changed via the slider 34 | * @param newThickness - New brush size 35 | */ 36 | onThicknessChange?: (newThickness: number) => void; 37 | 38 | /** 39 | * Callback when brush opacity is changed via the slider 40 | * @param newOpacity - New brush opacity 41 | */ 42 | onOpacityChange?: (newOpacity: number) => void; 43 | 44 | /** 45 | * Step value of the opacity slider, should be between 0 and 1 46 | * @default DEFAULT_OPACITY_STEP 47 | */ 48 | opacityStep?: number; 49 | 50 | /** 51 | * Minimum value of the thickness slider 52 | * @default DEFAULT_THICKNESS_MIN 53 | */ 54 | thicknessMin?: number; 55 | 56 | /** 57 | * Maximum value of the thickness slider 58 | * @default DEFAULT_THICKNESS_MAX 59 | */ 60 | thicknessMax?: number; 61 | 62 | /** 63 | * Step value of the thickness slider, should be between `props.thicknessMin` and `props.thicknessMax` 64 | * @default DEFAULT_THICKNESS_STEP 65 | */ 66 | thicknessStep?: number; 67 | 68 | /** 69 | * Slider color 70 | * @default DEFAULT_SLIDER_COLOR 71 | */ 72 | sliderColor?: string; 73 | 74 | /** 75 | * Style of the container 76 | */ 77 | style?: StyleProp; 78 | } 79 | 80 | export interface BrushPropertiesRef { 81 | height: number; 82 | } 83 | 84 | /** 85 | * Component allowing user to change brush properties, such as the color, 86 | * thickness, and opacity. 87 | * 88 | * If no thickness or opacity is provided, the component will behave like the 89 | * `ColorPicker` component. 90 | */ 91 | const BrushProperties = forwardRef( 92 | ( 93 | { 94 | thickness = DEFAULT_THICKNESS, 95 | opacity = DEFAULT_OPACITY, 96 | onThicknessChange, 97 | onOpacityChange, 98 | opacityStep = DEFAULT_OPACITY_STEP, 99 | thicknessMin = DEFAULT_THICKNESS_MIN, 100 | thicknessMax = DEFAULT_THICKNESS_MAX, 101 | thicknessStep = DEFAULT_THICKNESS_STEP, 102 | sliderColor = DEFAULT_SLIDER_COLOR, 103 | color, 104 | onColorChange, 105 | colors = DEFAULT_COLORS, 106 | style, 107 | }, 108 | ref 109 | ) => { 110 | const height = useMemo( 111 | () => 112 | (colors.length - 1) * 3 + 113 | (colors[0].length + colors[1].length) * colorButtonSize + 114 | SLIDERS_HEIGHT, 115 | [colors] 116 | ); 117 | 118 | useImperativeHandle(ref, () => ({ 119 | height, 120 | })); 121 | 122 | return ( 123 | 124 | 129 | {thickness && onThicknessChange && opacity && onOpacityChange && ( 130 | 131 | {thickness && onThicknessChange && ( 132 | 141 | )} 142 | {opacity && onOpacityChange && ( 143 | 152 | )} 153 | 154 | )} 155 | 156 | ); 157 | } 158 | ); 159 | 160 | const styles = StyleSheet.create({ 161 | sliderContainer: { 162 | marginVertical: 10, 163 | }, 164 | }); 165 | 166 | export default BrushProperties; 167 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/brushProperties/colorPicker/ColorButton.tsx: -------------------------------------------------------------------------------- 1 | import React, { memo } from 'react'; 2 | import { TouchableOpacity, StyleSheet, Dimensions, View } from 'react-native'; 3 | 4 | import { isBright } from '../../utils'; 5 | 6 | const { width } = Dimensions.get('screen'); 7 | export const colorButtonSize = Math.min(Math.round((width - 40) / 12), 50); 8 | 9 | interface ColorButtonProps { 10 | /** 11 | * Color of the button 12 | */ 13 | color: string; 14 | 15 | /** 16 | * Wether the button is selected or not 17 | * @default false 18 | */ 19 | selected?: boolean; 20 | 21 | /** 22 | * Callback the button is pressed 23 | * @param color Color of the button 24 | */ 25 | onPress: (color: string) => void; 26 | 27 | /** 28 | * Wether the button is the top left corner 29 | * @default false 30 | */ 31 | isTopStart: boolean; 32 | 33 | /** 34 | * Wether the button is the top right corner 35 | * @default false 36 | */ 37 | isTopEnd: boolean; 38 | 39 | /** 40 | * Wether the button is the bottom left corner 41 | * @default false 42 | */ 43 | isBottomStart: boolean; 44 | 45 | /** 46 | * Wether the button is the bottom right corner 47 | * @default false 48 | */ 49 | isBottomEnd: boolean; 50 | } 51 | 52 | /** 53 | * Buttons displaying a color in the `ColorPicker` component 54 | */ 55 | const ColorButton: React.FC = ({ 56 | color, 57 | selected, 58 | onPress, 59 | isTopStart, 60 | isTopEnd, 61 | isBottomStart, 62 | isBottomEnd, 63 | }) => { 64 | const handleOnPress = () => onPress(color); 65 | 66 | const borderRadiusStyle = { 67 | borderTopStartRadius: isTopStart ? 8 : 0, 68 | borderTopEndRadius: isTopEnd ? 8 : 0, 69 | borderBottomStartRadius: isBottomStart ? 8 : 0, 70 | borderBottomEndRadius: isBottomEnd ? 8 : 0, 71 | }; 72 | 73 | const style = { 74 | backgroundColor: color, 75 | borderWidth: selected ? 2 : 0, 76 | borderColor: isBright(color) ? '#000000b0' : '#ffffffb0', 77 | }; 78 | 79 | return ( 80 | 81 | 85 | 86 | ); 87 | }; 88 | 89 | const styles = StyleSheet.create({ 90 | button: { 91 | height: colorButtonSize, 92 | width: colorButtonSize, 93 | borderWidth: 3, 94 | }, 95 | }); 96 | 97 | export default memo(ColorButton); 98 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/brushProperties/colorPicker/ColorPicker.tsx: -------------------------------------------------------------------------------- 1 | import React, { memo } from 'react'; 2 | import { StyleProp, StyleSheet, View, ViewStyle } from 'react-native'; 3 | 4 | import { DEFAULT_COLORS } from '../../constants'; 5 | import ColorButton from './ColorButton'; 6 | 7 | export interface ColorPickerProps { 8 | /** 9 | * Brush color, one from the colors provided 10 | */ 11 | color: string; 12 | 13 | /** 14 | * Callback when a color is selected 15 | * @param newColor - New selected color 16 | */ 17 | onColorChange: (newColor: string) => void; 18 | 19 | /** 20 | * Color picker colors, specifying the color picker sections each 21 | * containing rows of colors. First array defines the sections, second 22 | * one defines the rows, and the last one defines the columns. 23 | * @default DEFAULT_COLORS 24 | */ 25 | colors?: string[][][]; 26 | 27 | /** 28 | * Style of the container 29 | */ 30 | style?: StyleProp; 31 | } 32 | 33 | /** 34 | * Color picker component displaying a grid of colors triggering a 35 | * callback when a color is selected and being able to select a color 36 | */ 37 | const ColorPicker: React.FC = ({ 38 | color, 39 | onColorChange, 40 | colors = DEFAULT_COLORS, 41 | style, 42 | }) => ( 43 | 44 | 45 | {colors.map((section, gKey) => ( 46 | 50 | {section.map((row, rKey) => ( 51 | 52 | {row.map((buttonColor, colorKey) => ( 53 | 66 | ))} 67 | 68 | ))} 69 | 70 | ))} 71 | 72 | 73 | ); 74 | 75 | const styles = StyleSheet.create({ 76 | row: { 77 | flexDirection: 'row', 78 | }, 79 | content: { 80 | borderRadius: 10, 81 | flex: 1, 82 | }, 83 | container: { 84 | borderRadius: 10, 85 | left: 0, 86 | right: 0, 87 | alignItems: 'center', 88 | justifyContent: 'center', 89 | }, 90 | divider: { 91 | marginBottom: 3, 92 | }, 93 | }); 94 | 95 | export default memo(ColorPicker); 96 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/constants.ts: -------------------------------------------------------------------------------- 1 | import { DrawingTool } from './types'; 2 | 3 | const grayscale = [ 4 | [ 5 | '#010101', 6 | '#151515', 7 | '#2A2A2A', 8 | '#3E3E3E', 9 | '#535353', 10 | '#666666', 11 | '#7A7A7A', 12 | '#8F8F8F', 13 | '#A3A3A3', 14 | '#B8B8B8', 15 | '#CCCCCC', 16 | '#FFFFFF', 17 | ], 18 | ]; 19 | 20 | const colors = [ 21 | [ 22 | '#457429', 23 | '#696F1C', 24 | '#6B6414', 25 | '#8C6115', 26 | '#8D5014', 27 | '#89280C', 28 | '#81090A', 29 | '#95133F', 30 | '#8204A6', 31 | '#3704AB', 32 | '#003389', 33 | '#0086AB', 34 | ], 35 | [ 36 | '#75BD4F', 37 | '#B5C835', 38 | '#C1BB2C', 39 | '#FFC934', 40 | '#FFAA2E', 41 | '#FF6924', 42 | '#F42C1B', 43 | '#DB4575', 44 | '#B644D0', 45 | '#7A4DD9', 46 | '#0063FA', 47 | '#00C7FC', 48 | ], 49 | [ 50 | '#A9D78A', 51 | '#E7F169', 52 | '#FFF755', 53 | '#FFD367', 54 | '#FFBE61', 55 | '#FF8F5B', 56 | '#FF6252', 57 | '#EC86A8', 58 | '#CE82E8', 59 | '#AB88F2', 60 | '#4897FA', 61 | '#5ADDFC', 62 | ], 63 | [ 64 | '#D6EFC3', 65 | '#F8FAB0', 66 | '#FFFA9E', 67 | '#FFE7AD', 68 | '#FFD9AC', 69 | '#FFC0A9', 70 | '#FFA9A7', 71 | '#FDC2D7', 72 | '#EDC1F9', 73 | '#D1C4F8', 74 | '#A2C4FB', 75 | '#AFEBFE', 76 | ], 77 | ]; 78 | 79 | export const DEFAULT_COLORS = [colors, grayscale]; 80 | export const DEFAULT_THICKNESS = 3; 81 | export const DEFAULT_OPACITY = 1; 82 | export const DEFAULT_TOOL = DrawingTool.Brush; 83 | export const DEFAULT_BRUSH_PREVIEW = 'stroke'; 84 | export const DEFAULT_OPACITY_STEP = 0.1; 85 | export const DEFAULT_THICKNESS_MIN = 5; 86 | export const DEFAULT_THICKNESS_MAX = 35; 87 | export const DEFAULT_THICKNESS_STEP = 1; 88 | export const DEFAULT_SLIDER_COLOR = '#000'; 89 | export const DEFAULT_DELETE_BUTTON_COLOR = '#81090A'; 90 | export const DEFAULT_OTHER_BUTTONS_COLOR = '#DDD'; 91 | export const SLIDERS_HEIGHT = 80; 92 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/icons/Brush.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Svg, { Path, SvgProps } from 'react-native-svg'; 3 | 4 | const Brush = (props: SvgProps) => ( 5 | 6 | 7 | 8 | 9 | ); 10 | 11 | const MemoBrush = React.memo(Brush); 12 | export default MemoBrush; 13 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/icons/Delete.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Svg, { Path, SvgProps } from 'react-native-svg'; 3 | 4 | const Delete = (props: SvgProps) => ( 5 | 6 | 7 | 8 | 9 | ); 10 | 11 | const MemoDelete = React.memo(Delete); 12 | export default MemoDelete; 13 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/icons/Eraser.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Svg, { Path, SvgProps } from 'react-native-svg'; 3 | 4 | const Eraser = (props: SvgProps) => ( 5 | 6 | 7 | 8 | ); 9 | 10 | const MemoEraser = React.memo(Eraser); 11 | export default MemoEraser; 12 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/icons/Palette.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Svg, { Path, SvgProps } from 'react-native-svg'; 3 | 4 | const Palette = (props: SvgProps) => ( 5 | 6 | 7 | 8 | 9 | ); 10 | 11 | const MemoPalette = React.memo(Palette); 12 | export default MemoPalette; 13 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/icons/Undo.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Svg, { Path, SvgProps } from 'react-native-svg'; 3 | 4 | const Undo = (props: SvgProps) => ( 5 | 6 | 7 | 8 | 9 | ); 10 | 11 | const MemoUndo = React.memo(Undo); 12 | export default MemoUndo; 13 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/icons/index.ts: -------------------------------------------------------------------------------- 1 | export { default as Delete } from './Delete'; 2 | export { default as Palette } from './Palette'; 3 | export { default as Brush } from './Brush'; 4 | export { default as Undo } from './Undo'; 5 | export { default as Eraser } from './Eraser'; 6 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/index.tsx: -------------------------------------------------------------------------------- 1 | export { 2 | default as CanvasControls, 3 | CanvasControlsProps, 4 | } from './CanvasControls'; 5 | 6 | export { 7 | default as BrushProperties, 8 | BrushPropertiesProps, 9 | BrushPropertiesRef, 10 | } from './brushProperties/BrushProperties'; 11 | 12 | export { 13 | default as BrushPreview, 14 | BrushPreviewProps, 15 | BrushType, 16 | } from './BrushPreview'; 17 | 18 | export { 19 | default as ColorPicker, 20 | ColorPickerProps, 21 | } from './brushProperties/colorPicker/ColorPicker'; 22 | 23 | export * from './types'; 24 | export * from './utils'; 25 | export * from './constants'; 26 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/types.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Tool used on the canvas 3 | */ 4 | export enum DrawingTool { 5 | Brush = 'brush', 6 | Eraser = 'eraser', 7 | } 8 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/src/utils.ts: -------------------------------------------------------------------------------- 1 | export const isBright = (color: string): boolean => { 2 | let rgb: number[] = []; 3 | 4 | if (color[0] === '#') { 5 | if (color.length === 7) { 6 | rgb = [ 7 | parseInt(color.substr(1, 2), 16), 8 | parseInt(color.substr(3, 2), 16), 9 | parseInt(color.substr(5, 2), 16), 10 | ]; 11 | } else if (color.length === 4) { 12 | return isBright( 13 | `#${color[1]}${color[1]}${color[2]}${color[2]}${color[3]}${color[3]}` 14 | ); 15 | } 16 | } 17 | 18 | if (rgb.length === 0) { 19 | return false; 20 | } 21 | 22 | // http://www.w3.org/TR/AERT#color-contrast 23 | const brightness = Math.round( 24 | (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000 25 | ); 26 | 27 | return brightness > 125; 28 | }; 29 | -------------------------------------------------------------------------------- /packages/react-native-draw-extras/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig", 3 | "compilerOptions": { 4 | "outDir": "./lib/typescript" 5 | } 6 | } -------------------------------------------------------------------------------- /packages/react-native-draw/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. 5 | 6 | ## [0.8.3](https://github.com/BenJeau/react-native-draw/compare/@benjeau/react-native-draw@0.8.1...@benjeau/react-native-draw@0.8.3) (2022-05-18) 7 | 8 | 9 | ### Bug Fixes 10 | 11 | * potential fix for types in IDE ([ebda3ca](https://github.com/BenJeau/react-native-draw/commit/ebda3cac6b941ecf807444f1c1d6d08fda6c6012)) 12 | * proper fix for types in IDEs ([719f45e](https://github.com/BenJeau/react-native-draw/commit/719f45e998f48a0753e9c596fa10952b48cce635)) 13 | 14 | 15 | 16 | 17 | 18 | ## [0.8.2](https://github.com/BenJeau/react-native-draw/compare/@benjeau/react-native-draw@0.8.1...@benjeau/react-native-draw@0.8.2) (2022-05-18) 19 | 20 | 21 | ### Bug Fixes 22 | 23 | * potential fix for types in IDE ([ebda3ca](https://github.com/BenJeau/react-native-draw/commit/ebda3cac6b941ecf807444f1c1d6d08fda6c6012)) 24 | 25 | 26 | 27 | 28 | 29 | ## [0.8.1](https://github.com/BenJeau/react-native-draw/compare/@benjeau/react-native-draw@0.8.0...@benjeau/react-native-draw@0.8.1) (2022-04-03) 30 | 31 | 32 | ### Features 33 | 34 | * added enabled prop to Canvas ([#57](https://github.com/BenJeau/react-native-draw/issues/57)) ([340d51f](https://github.com/BenJeau/react-native-draw/commit/340d51f19b9777532d255f59b3fdb347f9fb9218)) 35 | 36 | 37 | 38 | 39 | 40 | # [0.8.0](https://github.com/BenJeau/react-native-draw/compare/@benjeau/react-native-draw@0.7.0...@benjeau/react-native-draw@0.8.0) (2022-03-23) 41 | 42 | 43 | ### Bug Fixes 44 | 45 | * link to extras ([6fee493](https://github.com/BenJeau/react-native-draw/commit/6fee493e16d90e8160d7ece2a60dea241889ac05)) 46 | 47 | 48 | ### Features 49 | 50 | * make publish config public ([08b78aa](https://github.com/BenJeau/react-native-draw/commit/08b78aaa977c8e6211c902f52f24e407f4ee0a18)) 51 | 52 | 53 | 54 | 55 | 56 | # 0.7.0 (2022-02-07) 57 | 58 | 59 | ### Features 60 | 61 | * big refactor to eliminate the need of unused parts ([#44](https://github.com/BenJeau/react-native-draw/issues/44)) ([9a88db9](https://github.com/BenJeau/react-native-draw/commit/9a88db958fbc2b6a64cbe7e4f58bac6f600912ad)) 62 | -------------------------------------------------------------------------------- /packages/react-native-draw/README.md: -------------------------------------------------------------------------------- 1 | # @benjeau/react-native-draw 2 | 3 | [![NPM badge](https://img.shields.io/npm/v/@benjeau/react-native-draw)](https://www.npmjs.com/package/@benjeau/react-native-draw) [![CircleCI Status](https://img.shields.io/circleci/build/gh/BenJeau/react-native-draw)](https://app.circleci.com/pipelines/github/BenJeau/react-native-draw) ![Platform badge](https://img.shields.io/badge/platform-android%20%7C%20ios%20%7C%20web-blue) 4 | 5 | Cross-platform React Native drawing component based on SVG 6 | 7 | ## Installation 8 | 9 | ```sh 10 | npm install @benjeau/react-native-draw 11 | # or 12 | yarn add @benjeau/react-native-draw 13 | ``` 14 | 15 | > Also, you need to install [react-native-gesture-handler](https://github.com/software-mansion/react-native-gesture-handler) and [react-native-svg](https://github.com/react-native-svg/react-native-svg), and follow their installation instructions. 16 | 17 | ### Extras 18 | 19 | Supporting components, such as `CanvasControls`, `ColorPicker` and `BrushProperties` components, are available as a separate package, [`@benjeau/react-native-draw-extras`](https://github.com/BenJeau/react-native-draw/tree/master/packages/react-native-draw-extras) 20 | 21 | ## Usage 22 | 23 | > All the following examples are also available in the [example](./example/) Expo application 24 | 25 | ### Simple example 26 | 27 | Here's the most simple example: 28 | 29 | ```tsx 30 | import React from 'react'; 31 | import { Canvas } from '@benjeau/react-native-draw'; 32 | 33 | export default () => ; 34 | ``` 35 | 36 | https://user-images.githubusercontent.com/22248828/152838002-3bf01ff0-8c8d-43ec-abdf-4f856d200bc5.mp4 37 | 38 | ### Complex example 39 | 40 | Here's a more complex example: 41 | 42 |
43 | Complex example - Code snippet 44 | 45 | ```tsx 46 | import React, { useRef } from 'react'; 47 | import { Button } from 'react-native'; 48 | import { Canvas, CanvasRef } from '@benjeau/react-native-draw'; 49 | 50 | export default () => { 51 | const canvasRef = useRef(null); 52 | 53 | const handleUndo = () => { 54 | canvasRef.current?.undo(); 55 | }; 56 | 57 | const handleClear = () => { 58 | canvasRef.current?.clear(); 59 | }; 60 | 61 | return ( 62 | <> 63 | 71 |
78 | 79 | https://user-images.githubusercontent.com/22248828/152837975-a51bdcf5-9a62-4aa2-8e5e-26c1d52fcf79.mp4 80 | 81 | ### Example with `@BenJeau/react-native-draw-extras` 82 | 83 | This uses the [`@benjeau/react-native-draw-extras`](https://github.com/BenJeau/react-native-draw/tree/master/packages/react-native-draw-extras) npm package for the color picker and the bottom buttons/brush preview. 84 | 85 | > As this package does not depend on `@BenJeau/react-native-draw-extras`, it is completely optional and you can build your own supporting UI, just like the previous example 86 | 87 |
88 | Extras example - Code snippet 89 | 90 | ```tsx 91 | import React, { useRef, useState } from 'react'; 92 | import { Animated, StyleSheet, View } from 'react-native'; 93 | import { 94 | BrushProperties, 95 | Canvas, 96 | CanvasControls, 97 | CanvasRef, 98 | DEFAULT_COLORS, 99 | DrawingTool, 100 | } from '@benjeau/react-native-draw'; 101 | 102 | export default () => { 103 | const canvasRef = useRef(null); 104 | 105 | const [color, setColor] = useState(DEFAULT_COLORS[0][0][0]); 106 | const [thickness, setThickness] = useState(5); 107 | const [opacity, setOpacity] = useState(1); 108 | const [tool, setTool] = useState(DrawingTool.Brush); 109 | const [visibleBrushProperties, setVisibleBrushProperties] = useState(false); 110 | 111 | const handleUndo = () => { 112 | canvasRef.current?.undo(); 113 | }; 114 | 115 | const handleClear = () => { 116 | canvasRef.current?.clear(); 117 | }; 118 | 119 | const handleToggleEraser = () => { 120 | setTool((prev) => 121 | prev === DrawingTool.Brush ? DrawingTool.Eraser : DrawingTool.Brush 122 | ); 123 | }; 124 | 125 | const [overlayOpacity] = useState(new Animated.Value(0)); 126 | const handleToggleBrushProperties = () => { 127 | if (!visibleBrushProperties) { 128 | setVisibleBrushProperties(true); 129 | 130 | Animated.timing(overlayOpacity, { 131 | toValue: 1, 132 | duration: 200, 133 | useNativeDriver: true, 134 | }).start(); 135 | } else { 136 | Animated.timing(overlayOpacity, { 137 | toValue: 0, 138 | duration: 200, 139 | useNativeDriver: true, 140 | }).start(() => { 141 | setVisibleBrushProperties(false); 142 | }); 143 | } 144 | }; 145 | 146 | return ( 147 | <> 148 | 160 | 161 | 171 | {visibleBrushProperties && ( 172 | 194 | )} 195 | 196 | 197 | ); 198 | }; 199 | ``` 200 |
201 | 202 | https://user-images.githubusercontent.com/22248828/152837922-757d3a13-1d35-409a-936a-b38ea9248262.mp4 203 | 204 | ## Props 205 | 206 | ### Canvas 207 | 208 | | name | description | type | default | 209 | | ----------------------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------- | ----------------------------- | 210 | | `color` | Color of the brush strokes | `string` | - (required) | 211 | | `thickness` | Thickness of the brush strokes | `number` | - (required) | 212 | | `opacity` | Opacity of the brush strokes | `number` | - (required) | 213 | | `initialPaths` | Paths to be already drawn | `PathType[]` | `[]` | 214 | | `height` | Height of the canvas | `number` | height of the window - 80 | 215 | | `width` | Width of the canvas | `number` | width of the window | 216 | | `style` | Override the style of the container of the canvas | `StyleProp` | - | 217 | | `onPathsChange` | Callback function when paths change | (paths: [`PathType`](./src/types.ts)[]) => any | - | 218 | | `simplifyOptions` | SVG simplification options | [`SimplifyOptions`](./src/Draw.tsx) | see [below](#SimplifyOptions) | 219 | | `eraserSize` | Width of eraser (to compensate for path simplification) | `number` | `5` | 220 | | `tool` | Initial tool of the canvas | `brush` or `eraser` | `brush` | 221 | | `combineWithLatestPath` | Combine current path with the last path if it's the same color, thickness, and opacity | `boolean` | `false` | 222 | | `enabled` | Allows for the canvas to be drawn on, put to false if you want to disable/lock the canvas | `boolean` | `true` | 223 | 224 | ### SimplifyOptions 225 | 226 | | name | description | type | default | 227 | | --------------------- | ----------------------------------------------------------------------------- | --------- | ------- | 228 | | `simplifyPaths` | Enable SVG path simplification on paths, except the one currently being drawn | `boolean` | `true` | 229 | | `simplifyCurrentPath` | Enable SVG path simplification on the stroke being drawn | `boolean` | `false` | 230 | | `amount` | Amount of simplification to apply | `number` | `10` | 231 | | `roundPoints` | Ignore fractional part in the points. Improves performance | `boolean` | `true` | 232 | 233 | ## Ref functions 234 | 235 | | name | description | type | 236 | | ---------- | ------------------------------------------ | -------------------------- | 237 | | `undo` | Undo last brush stroke | `() => void` | 238 | | `clear` | Removes all brush strokes | `() => void` | 239 | | `getPaths` | Get brush strokes data | `() => PathType[]` | 240 | | `addPath` | Append a path to the current drawing paths | `(path: PathType) => void` | 241 | | `getSvg` | Get SVG path string of the drawing | `() => string` | 242 | 243 | ## Troubleshooting 244 | 245 | If you cannot draw on the canvas, make sure you have followed the extra steps of [react-native-gesture-handler](https://github.com/software-mansion/react-native-gesture-handler) 246 | 247 | ## Helper functions 248 | 249 | * If you need to create an SVG path, `createSVGPath()` is available to create the string representation of an SVG path. 250 | 251 | ## Contributing 252 | 253 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. 254 | 255 | ## License 256 | 257 | MIT 258 | -------------------------------------------------------------------------------- /packages/react-native-draw/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@benjeau/react-native-draw", 3 | "version": "0.8.3", 4 | "description": "Cross-platform React Native drawing component", 5 | "main": "lib/commonjs/index", 6 | "module": "lib/module/index", 7 | "types": "lib/typescript/src/index.d.ts", 8 | "react-native": "src/index", 9 | "source": "src/index", 10 | "scripts": { 11 | "prepare": "bob build" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/BenJeau/react-native-draw.git", 16 | "directory": "packages/react-native-draw" 17 | }, 18 | "author": "Benoit Jeaurond (https://github.com/BenJeau)", 19 | "license": "MIT", 20 | "bugs": { 21 | "url": "https://github.com/BenJeau/react-native-draw/issues" 22 | }, 23 | "files": [ 24 | "src", 25 | "lib" 26 | ], 27 | "publishConfig": { 28 | "access": "public", 29 | "registry": "https://registry.npmjs.org/" 30 | }, 31 | "homepage": "https://github.com/BenJeau/react-native-draw#readme", 32 | "keywords": [ 33 | "react-native-component", 34 | "react-component", 35 | "react-native", 36 | "ios", 37 | "android", 38 | "draw", 39 | "svg" 40 | ], 41 | "dependencies": { 42 | "@luncheon/simplify-svg-path": "^0.2.0" 43 | }, 44 | "devDependencies": { 45 | "@types/react": "^17.0.1", 46 | "@types/react-native": "0.64.3", 47 | "react": "17.0.1", 48 | "react-native": "0.64.3", 49 | "react-native-builder-bob": "^0.18.2", 50 | "react-native-gesture-handler": "^2.1.0", 51 | "react-native-svg": "^12.1.1", 52 | "typescript": "^4.5.5" 53 | }, 54 | "peerDependencies": { 55 | "react": "*", 56 | "react-native": "*", 57 | "react-native-gesture-handler": ">=2.0.0", 58 | "react-native-svg": ">=12.0.0" 59 | }, 60 | "react-native-builder-bob": { 61 | "source": "src", 62 | "output": "lib", 63 | "targets": [ 64 | "commonjs", 65 | "module", 66 | "typescript" 67 | ] 68 | }, 69 | "gitHead": "35dacae8f6063d0394ca5eda3691a0525c9b1100" 70 | } 71 | -------------------------------------------------------------------------------- /packages/react-native-draw/src/Canvas.tsx: -------------------------------------------------------------------------------- 1 | import React, { 2 | forwardRef, 3 | useEffect, 4 | useImperativeHandle, 5 | useState, 6 | } from 'react'; 7 | import { 8 | Animated, 9 | Dimensions, 10 | StyleProp, 11 | StyleSheet, 12 | View, 13 | ViewStyle, 14 | } from 'react-native'; 15 | import { 16 | Gesture, 17 | GestureDetector, 18 | GestureHandlerRootView, 19 | } from 'react-native-gesture-handler'; 20 | 21 | import { 22 | DEFAULT_BRUSH_COLOR, 23 | DEFAULT_ERASER_SIZE, 24 | DEFAULT_OPACITY, 25 | DEFAULT_THICKNESS, 26 | DEFAULT_TOOL, 27 | } from './constants'; 28 | import { DrawingTool, PathDataType, PathType } from './types'; 29 | import { createSVGPath } from './utils'; 30 | import SVGRenderer from './renderer/SVGRenderer'; 31 | import RendererHelper from './renderer/RendererHelper'; 32 | 33 | const { width: screenWidth, height: screenHeight } = Dimensions.get('window'); 34 | 35 | export interface CanvasProps { 36 | /** 37 | * Color of the brush strokes 38 | * @default DEFAULT_BRUSH_COLOR 39 | */ 40 | color?: string; 41 | 42 | /** 43 | * Thickness of the brush strokes 44 | * @default DEFAULT_THICKNESS 45 | */ 46 | thickness?: number; 47 | 48 | /** 49 | * Opacity of the brush strokes 50 | * @default DEFAULT_OPACITY 51 | */ 52 | opacity?: number; 53 | 54 | /** 55 | * Paths to be already drawn 56 | * @default [] 57 | */ 58 | initialPaths?: PathType[]; 59 | 60 | /** 61 | * Height of the canvas 62 | */ 63 | height?: number; 64 | 65 | /** 66 | * Width of the canvas 67 | */ 68 | width?: number; 69 | 70 | /** 71 | * Override the style of the container of the canvas 72 | */ 73 | style?: StyleProp; 74 | 75 | /** 76 | * Callback function when paths change 77 | */ 78 | onPathsChange?: (paths: PathType[]) => any; 79 | 80 | /** 81 | * SVG simplification options 82 | */ 83 | simplifyOptions?: SimplifyOptions; 84 | 85 | /** 86 | * Width of eraser (to compensate for path simplification) 87 | * @default DEFAULT_ERASER_SIZE 88 | */ 89 | eraserSize?: number; 90 | 91 | /** 92 | * Initial tool of the canvas 93 | * @default DEFAULT_TOOL 94 | */ 95 | tool?: DrawingTool; 96 | 97 | /** 98 | * Combine current path with the last path if it's the same color, 99 | * thickness, and opacity. 100 | * 101 | * **Note**: changing this value while drawing will only be effective 102 | * on the next change to opacity, thickness, or color change 103 | * @default false 104 | */ 105 | combineWithLatestPath?: boolean; 106 | 107 | /** 108 | * Allows for the canvas to be drawn on, put to false if you want to disable/lock 109 | * the canvas 110 | * @default true 111 | */ 112 | enabled?: boolean; 113 | } 114 | 115 | export interface SimplifyOptions { 116 | /** 117 | * Enable SVG path simplification on paths, except the one currently being drawn 118 | */ 119 | simplifyPaths?: boolean; 120 | 121 | /** 122 | * Enable SVG path simplification on the stroke being drawn 123 | */ 124 | simplifyCurrentPath?: boolean; 125 | 126 | /** 127 | * Amount of simplification to apply 128 | */ 129 | amount?: number; 130 | 131 | /** 132 | * Ignore fractional part in the points. Improves performance 133 | */ 134 | roundPoints?: boolean; 135 | } 136 | 137 | export interface CanvasRef { 138 | /** 139 | * Undo last brush stroke 140 | */ 141 | undo: () => void; 142 | 143 | /** 144 | * Removes all brush strokes 145 | */ 146 | clear: () => void; 147 | 148 | /** 149 | * Get brush strokes data 150 | */ 151 | getPaths: () => PathType[]; 152 | 153 | /** 154 | * Append a path to the current drawing paths 155 | * @param path Path to append/draw 156 | */ 157 | addPath: (path: PathType) => void; 158 | 159 | /** 160 | * Get SVG path string of the drawing 161 | */ 162 | getSvg: () => string; 163 | } 164 | 165 | /** 166 | * Generate SVG path string. Helper method for createSVGPath 167 | * 168 | * @param paths SVG path data 169 | * @param simplifyOptions Simplification options for the SVG drawing simplification 170 | * @returns SVG path strings 171 | */ 172 | const generateSVGPath = ( 173 | path: PathDataType, 174 | simplifyOptions: SimplifyOptions 175 | ) => 176 | createSVGPath( 177 | path, 178 | simplifyOptions.simplifyPaths ? simplifyOptions.amount! : 0, 179 | simplifyOptions.roundPoints! 180 | ); 181 | 182 | /** 183 | * Generate multiple SVG path strings. If the path string is already defined, do not create a new one. 184 | * 185 | * @param paths SVG data paths 186 | * @param simplifyOptions Simplification options for the SVG drawing simplification 187 | * @returns An array of SVG path strings 188 | */ 189 | const generateSVGPaths = ( 190 | paths: PathType[], 191 | simplifyOptions: SimplifyOptions 192 | ) => 193 | paths.map((i) => ({ 194 | ...i, 195 | path: i.path 196 | ? i.path 197 | : i.data.reduce( 198 | (acc: string[], data) => [ 199 | ...acc, 200 | generateSVGPath(data, simplifyOptions), 201 | ], 202 | [] 203 | ), 204 | })); 205 | 206 | const Canvas = forwardRef( 207 | ( 208 | { 209 | color = DEFAULT_BRUSH_COLOR, 210 | thickness = DEFAULT_THICKNESS, 211 | opacity = DEFAULT_OPACITY, 212 | initialPaths = [], 213 | style, 214 | height = screenHeight - 80, 215 | width = screenWidth, 216 | simplifyOptions = {}, 217 | onPathsChange, 218 | eraserSize = DEFAULT_ERASER_SIZE, 219 | tool = DEFAULT_TOOL, 220 | combineWithLatestPath = false, 221 | enabled = true, 222 | }, 223 | ref 224 | ) => { 225 | simplifyOptions = { 226 | simplifyPaths: true, 227 | simplifyCurrentPath: false, 228 | amount: 15, 229 | roundPoints: true, 230 | ...simplifyOptions, 231 | }; 232 | 233 | const [paths, setPaths] = useState( 234 | generateSVGPaths(initialPaths, simplifyOptions) 235 | ); 236 | const [path, setPath] = useState([]); 237 | 238 | const canvasContainerStyles = [ 239 | styles.canvas, 240 | { 241 | height, 242 | width, 243 | }, 244 | style, 245 | ]; 246 | 247 | const addPointToPath = (x: number, y: number) => { 248 | setPath((prev) => [ 249 | ...prev, 250 | [ 251 | simplifyOptions.roundPoints ? Math.floor(x) : x, 252 | simplifyOptions.roundPoints ? Math.floor(y) : y, 253 | ], 254 | ]); 255 | }; 256 | 257 | const undo = () => { 258 | setPaths((list) => 259 | list.reduce((acc: PathType[], p, index) => { 260 | if (index === list.length - 1) { 261 | if (p.data.length > 1) { 262 | return [ 263 | ...acc, 264 | { 265 | ...p, 266 | data: p.data.slice(0, -1), 267 | path: p.path!.slice(0, -1), 268 | }, 269 | ]; 270 | } 271 | return acc; 272 | } 273 | return [...acc, p]; 274 | }, []) 275 | ); 276 | }; 277 | 278 | const clear = () => { 279 | setPaths([]); 280 | setPath([]); 281 | }; 282 | 283 | const getPaths = () => paths; 284 | 285 | const addPath = (newPath: PathType) => 286 | setPaths((prev) => [...prev, newPath]); 287 | 288 | const getSvg = () => { 289 | const serializePath = ( 290 | d: string, 291 | stroke: string, 292 | strokeWidth: number, 293 | strokeOpacity: number 294 | ) => 295 | ``; 296 | 297 | const separatePaths = (p: PathType) => 298 | p.path!.reduce( 299 | (acc, innerPath) => 300 | `${acc}${serializePath( 301 | innerPath, 302 | p.color, 303 | p.thickness, 304 | p.opacity 305 | )}`, 306 | '' 307 | ); 308 | 309 | const combinedPath = (p: PathType) => 310 | `${serializePath(p.path!.join(' '), p.color, p.thickness, p.opacity)}`; 311 | 312 | const serializedPaths = paths.reduce( 313 | (acc, p) => `${acc}${p.combine ? combinedPath(p) : separatePaths(p)}`, 314 | '' 315 | ); 316 | 317 | return `${serializedPaths}`; 318 | }; 319 | 320 | useImperativeHandle(ref, () => ({ 321 | undo, 322 | clear, 323 | getPaths, 324 | addPath, 325 | getSvg, 326 | })); 327 | 328 | useEffect( 329 | () => onPathsChange && onPathsChange(paths), 330 | [paths, onPathsChange] 331 | ); 332 | 333 | const panGesture = Gesture.Pan() 334 | .onChange(({ x, y }) => { 335 | switch (tool) { 336 | case DrawingTool.Brush: 337 | addPointToPath(x, y); 338 | break; 339 | case DrawingTool.Eraser: 340 | setPaths((prevPaths) => 341 | prevPaths.reduce((acc: PathType[], p) => { 342 | const filteredDataPaths = p.data.reduce( 343 | ( 344 | acc2: { data: PathDataType[]; path: string[] }, 345 | data, 346 | index 347 | ) => { 348 | const closeToPath = data.some( 349 | ([x1, y1]) => 350 | Math.abs(x1 - x) < p.thickness + eraserSize && 351 | Math.abs(y1 - y) < p.thickness + eraserSize 352 | ); 353 | 354 | // If point close to path, don't include it 355 | if (closeToPath) { 356 | return acc2; 357 | } 358 | 359 | return { 360 | data: [...acc2.data, data], 361 | path: [...acc2.path, p.path![index]], 362 | }; 363 | }, 364 | { data: [], path: [] } 365 | ); 366 | 367 | if (filteredDataPaths.data.length > 0) { 368 | return [...acc, { ...p, ...filteredDataPaths }]; 369 | } 370 | 371 | return acc; 372 | }, []) 373 | ); 374 | break; 375 | } 376 | }) 377 | .onBegin(({ x, y }) => { 378 | if (tool === DrawingTool.Brush) { 379 | addPointToPath(x, y); 380 | } 381 | }) 382 | .onEnd(() => { 383 | if (tool === DrawingTool.Brush) { 384 | setPaths((prev) => { 385 | const newSVGPath = generateSVGPath(path, simplifyOptions); 386 | 387 | if (prev.length === 0) { 388 | return [ 389 | { 390 | color, 391 | path: [newSVGPath], 392 | data: [path], 393 | thickness, 394 | opacity, 395 | combine: combineWithLatestPath, 396 | }, 397 | ]; 398 | } 399 | 400 | const lastPath = prev[prev.length - 1]; 401 | 402 | // Check if the last path has the same properties 403 | if ( 404 | lastPath.color === color && 405 | lastPath.thickness === thickness && 406 | lastPath.opacity === opacity 407 | ) { 408 | lastPath.path = [...lastPath.path!, newSVGPath]; 409 | lastPath.data = [...lastPath.data, path]; 410 | 411 | return [...prev.slice(0, -1), lastPath]; 412 | } 413 | 414 | return [ 415 | ...prev, 416 | { 417 | color, 418 | path: [newSVGPath], 419 | data: [path], 420 | thickness, 421 | opacity, 422 | combine: combineWithLatestPath, 423 | }, 424 | ]; 425 | }); 426 | setPath([]); 427 | } 428 | }) 429 | .minPointers(1) 430 | .minDistance(0) 431 | .averageTouches(false) 432 | .hitSlop({ 433 | height, 434 | width, 435 | top: 0, 436 | left: 0, 437 | }) 438 | .shouldCancelWhenOutside(true) 439 | .enabled(enabled); 440 | 441 | return ( 442 | 443 | 444 | 445 | 446 | 462 | 463 | 464 | 465 | 466 | ); 467 | } 468 | ); 469 | 470 | const styles = StyleSheet.create({ 471 | canvas: { 472 | backgroundColor: 'white', 473 | }, 474 | canvasOverlay: { 475 | position: 'absolute', 476 | height: '100%', 477 | width: '100%', 478 | backgroundColor: '#000000', 479 | }, 480 | }); 481 | 482 | export default Canvas; 483 | -------------------------------------------------------------------------------- /packages/react-native-draw/src/constants.ts: -------------------------------------------------------------------------------- 1 | import { DrawingTool } from './types'; 2 | 3 | export const DEFAULT_BRUSH_COLOR = '#000000'; 4 | export const DEFAULT_ERASER_SIZE = 5; 5 | export const DEFAULT_THICKNESS = 3; 6 | export const DEFAULT_OPACITY = 1; 7 | export const DEFAULT_TOOL = DrawingTool.Brush; 8 | -------------------------------------------------------------------------------- /packages/react-native-draw/src/index.tsx: -------------------------------------------------------------------------------- 1 | export { 2 | default as Canvas, 3 | CanvasRef, 4 | CanvasProps, 5 | SimplifyOptions, 6 | } from './Canvas'; 7 | 8 | export * from './types'; 9 | export * from './utils'; 10 | export * from './constants'; 11 | -------------------------------------------------------------------------------- /packages/react-native-draw/src/renderer/RendererHelper.tsx: -------------------------------------------------------------------------------- 1 | import React, { useMemo } from 'react'; 2 | 3 | import type { PathDataType, PathType } from '../types'; 4 | import { createSVGPath } from '../utils'; 5 | 6 | export interface RendererProps { 7 | paths: PathType[]; 8 | height: number; 9 | width: number; 10 | } 11 | 12 | interface RendererHelperProps { 13 | currentPath: PathDataType; 14 | currentColor: string; 15 | currentThickness: number; 16 | currentOpacity: number; 17 | paths: PathType[]; 18 | height: number; 19 | width: number; 20 | roundPoints: boolean; 21 | currentPathTolerance: number; 22 | Renderer: React.FC; 23 | } 24 | 25 | const RendererHelper: React.FC = ({ 26 | currentPath, 27 | currentColor, 28 | currentThickness, 29 | currentOpacity, 30 | paths, 31 | height, 32 | width, 33 | roundPoints, 34 | currentPathTolerance, 35 | Renderer, 36 | }) => { 37 | const mergedPaths = useMemo( 38 | () => [ 39 | ...paths, 40 | { 41 | color: currentColor, 42 | path: [createSVGPath(currentPath, currentPathTolerance, roundPoints)], 43 | thickness: currentThickness, 44 | opacity: currentOpacity, 45 | data: [currentPath], 46 | }, 47 | ], 48 | [ 49 | currentColor, 50 | currentThickness, 51 | currentPath, 52 | currentOpacity, 53 | paths, 54 | currentPathTolerance, 55 | roundPoints, 56 | ] 57 | ); 58 | 59 | return ; 60 | }; 61 | 62 | export default RendererHelper; 63 | -------------------------------------------------------------------------------- /packages/react-native-draw/src/renderer/SVGRenderer.tsx: -------------------------------------------------------------------------------- 1 | import React, { useMemo } from 'react'; 2 | import Svg, { Path } from 'react-native-svg'; 3 | 4 | import type { RendererProps } from './RendererHelper'; 5 | 6 | const SVGRenderer: React.FC = ({ paths, height, width }) => ( 7 | 8 | {paths.map(({ color, path, thickness, opacity, combine }, i) => 9 | combine ? ( 10 | 17 | ) : ( 18 | path!.map((svgPath, j) => ( 19 | 29 | )) 30 | ) 31 | )} 32 | 33 | ); 34 | 35 | interface SVGRendererPathProps { 36 | path?: string[]; 37 | color: string; 38 | thickness: number; 39 | opacity: number; 40 | } 41 | 42 | const SVGRendererPath: React.FC = ({ 43 | path, 44 | color, 45 | thickness, 46 | opacity, 47 | }) => { 48 | const memoizedPath = useMemo(() => path?.join(' ') ?? '', [path]); 49 | 50 | return ( 51 | 60 | ); 61 | }; 62 | 63 | export default SVGRenderer; 64 | -------------------------------------------------------------------------------- /packages/react-native-draw/src/types.ts: -------------------------------------------------------------------------------- 1 | export type PathDataType = [number, number][]; 2 | 3 | export interface PathType { 4 | /** 5 | * Color of the path 6 | */ 7 | color: string; 8 | 9 | /** 10 | * SVG path. It does not need to be defined while passing a PathType to Draw as initialValues. 11 | * It will always be defined if you get the path data from the component. 12 | */ 13 | path?: string[]; 14 | 15 | /** 16 | * Raw points data used to create the SVG path 17 | */ 18 | data: PathDataType[]; 19 | 20 | /** 21 | * Thickness of the path 22 | */ 23 | thickness: number; 24 | 25 | /** 26 | * Opacity of the path 27 | */ 28 | opacity: number; 29 | 30 | /** 31 | * Combine all the paths 32 | */ 33 | combine?: boolean; 34 | } 35 | 36 | /** 37 | * Tool used on the canvas 38 | */ 39 | export enum DrawingTool { 40 | Brush = 'brush', 41 | Eraser = 'eraser', 42 | } 43 | -------------------------------------------------------------------------------- /packages/react-native-draw/src/utils.ts: -------------------------------------------------------------------------------- 1 | import simplifySvgPath from '@luncheon/simplify-svg-path'; 2 | import type { PathDataType } from './types'; 3 | 4 | export const createSVGPath = ( 5 | points: PathDataType, 6 | tolerance: number, 7 | roundPoints: boolean 8 | ) => { 9 | if (points.length > 1) { 10 | try { 11 | return simplifySvgPath(points, { 12 | precision: roundPoints ? 0 : 5, 13 | tolerance, 14 | }); 15 | } catch (error) { 16 | console.log(error); 17 | } 18 | } else if (points.length === 1) { 19 | return `M${points[0][0]},${points[0][1]} L${points[0][0]},${points[0][1]}`; 20 | } 21 | return ''; 22 | }; 23 | -------------------------------------------------------------------------------- /packages/react-native-draw/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig", 3 | "compilerOptions": { 4 | "outDir": "./lib/typescript" 5 | } 6 | } -------------------------------------------------------------------------------- /scripts/bootstrap.js: -------------------------------------------------------------------------------- 1 | const os = require('os'); 2 | const path = require('path'); 3 | const child_process = require('child_process'); 4 | 5 | const root = path.resolve(__dirname, '..'); 6 | const args = process.argv.slice(2); 7 | const options = { 8 | cwd: process.cwd(), 9 | env: process.env, 10 | stdio: 'inherit', 11 | encoding: 'utf-8', 12 | }; 13 | 14 | if (os.type() === 'Windows_NT') { 15 | options.shell = true; 16 | } 17 | 18 | let result; 19 | 20 | if (process.cwd() !== root || args.length) { 21 | // We're not in the root of the project, or additional arguments were passed 22 | // In this case, forward the command to `yarn` 23 | result = child_process.spawnSync('yarn', args, options); 24 | } else { 25 | // If `yarn` is run without arguments, perform bootstrap 26 | result = child_process.spawnSync('yarn', ['bootstrap'], options); 27 | } 28 | 29 | process.exitCode = result.status; 30 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "paths": { 5 | "@benjeau/react-native-draw": ["./packages/react-native-draw/src"], 6 | "@benjeau/react-native-draw-extras": [ 7 | "./packages/react-native-draw-extras/src" 8 | ] 9 | }, 10 | "allowUnreachableCode": false, 11 | "allowUnusedLabels": false, 12 | "esModuleInterop": true, 13 | "importsNotUsedAsValues": "error", 14 | "forceConsistentCasingInFileNames": true, 15 | "composite": true, 16 | "jsx": "react", 17 | "lib": ["esnext"], 18 | "module": "esnext", 19 | "moduleResolution": "node", 20 | "noFallthroughCasesInSwitch": true, 21 | "noImplicitReturns": true, 22 | "noImplicitUseStrict": false, 23 | "noStrictGenericChecks": false, 24 | "noUnusedLocals": true, 25 | "noUnusedParameters": true, 26 | "resolveJsonModule": true, 27 | "skipLibCheck": true, 28 | "strict": true, 29 | "target": "esnext" 30 | }, 31 | "exclude": [ 32 | "packages/*/lib", 33 | ] 34 | } 35 | --------------------------------------------------------------------------------