diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..de29e17 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,4 @@ +typings +node_modules +example/android-bundle.js +example/ios-bundle.js diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..761beda --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,297 @@ +module.exports = { + root: true, + + parser: "babel-eslint", + + env: { + es6: true + }, + + plugins: [ + "eslint-comments", + "flowtype", + "prettier", + "react", + "react-hooks", + "react-native", + "jest" + ], + + // Map from global var to bool specifying if it can be redefined + globals: { + __DEV__: true, + __dirname: false, + __fbBatchedBridgeConfig: false, + alert: false, + cancelAnimationFrame: false, + cancelIdleCallback: false, + clearImmediate: true, + clearInterval: false, + clearTimeout: false, + console: false, + document: false, + escape: false, + Event: false, + EventTarget: false, + exports: false, + fetch: false, + FormData: false, + global: false, + Map: true, + module: false, + navigator: false, + process: false, + Promise: true, + requestAnimationFrame: true, + requestIdleCallback: true, + require: false, + Set: true, + setImmediate: true, + setInterval: false, + setTimeout: false, + window: false, + XMLHttpRequest: false + }, + + rules: { + // General + "comma-dangle": [1, "always-multiline"], // allow or disallow trailing commas + "no-cond-assign": 1, // disallow assignment in conditional expressions + "no-console": 0, // disallow use of console (off by default in the node environment) + "no-const-assign": 2, // disallow assignment to const-declared variables + "no-constant-condition": 0, // disallow use of constant expressions in conditions + "no-control-regex": 1, // disallow control characters in regular expressions + "no-debugger": 1, // disallow use of debugger + "no-dupe-class-members": 2, // Disallow duplicate name in class members + "no-dupe-keys": 2, // disallow duplicate keys when creating object literals + "no-empty": 0, // disallow empty statements + "no-ex-assign": 1, // disallow assigning to the exception in a catch block + "no-extra-boolean-cast": 1, // disallow double-negation boolean casts in a boolean context + "no-extra-parens": 0, // disallow unnecessary parentheses (off by default) + "no-extra-semi": 1, // disallow unnecessary semicolons + "no-func-assign": 1, // disallow overwriting functions written as function declarations + "no-inner-declarations": 0, // disallow function or variable declarations in nested blocks + "no-invalid-regexp": 1, // disallow invalid regular expression strings in the RegExp constructor + "no-negated-in-lhs": 1, // disallow negation of the left operand of an in expression + "no-obj-calls": 1, // disallow the use of object properties of the global object (Math and JSON) as functions + "no-regex-spaces": 1, // disallow multiple spaces in a regular expression literal + "no-reserved-keys": 0, // disallow reserved words being used as object literal keys (off by default) + "no-sparse-arrays": 1, // disallow sparse arrays + "no-unreachable": 2, // disallow unreachable statements after a return, throw, continue, or break statement + "use-isnan": 1, // disallow comparisons with the value NaN + "valid-jsdoc": 0, // Ensure JSDoc comments are valid (off by default) + "valid-typeof": 1, // Ensure that the results of typeof are compared against a valid string + + // Best Practices + // These are rules designed to prevent you from making mistakes. They either prescribe a better way of doing something or help you avoid footguns. + + "block-scoped-var": 0, // treat var statements as if they were block scoped (off by default) + complexity: 0, // specify the maximum cyclomatic complexity allowed in a program (off by default) + "consistent-return": 0, // require return statements to either always or never specify values + curly: 1, // specify curly brace conventions for all control statements + "default-case": 0, // require default case in switch statements (off by default) + "dot-notation": 1, // encourages use of dot notation whenever possible + eqeqeq: [1, "allow-null"], // require the use of === and !== + "guard-for-in": 0, // make sure for-in loops have an if statement (off by default) + "no-alert": 1, // disallow the use of alert, confirm, and prompt + "no-caller": 1, // disallow use of arguments.caller or arguments.callee + "no-div-regex": 1, // disallow division operators explicitly at beginning of regular expression (off by default) + "no-else-return": 0, // disallow else after a return in an if (off by default) + "no-eq-null": 0, // disallow comparisons to null without a type-checking operator (off by default) + "no-eval": 2, // disallow use of eval() + "no-extend-native": 1, // disallow adding to native types + "no-extra-bind": 1, // disallow unnecessary function binding + "no-fallthrough": 1, // disallow fallthrough of case statements + "no-floating-decimal": 1, // disallow the use of leading or trailing decimal points in numeric literals (off by default) + "no-implied-eval": 1, // disallow use of eval()-like methods + "no-labels": 1, // disallow use of labeled statements + "no-iterator": 1, // disallow usage of __iterator__ property + "no-lone-blocks": 1, // disallow unnecessary nested blocks + "no-loop-func": 0, // disallow creation of functions within loops + "no-multi-str": 0, // disallow use of multiline strings + "no-native-reassign": 0, // disallow reassignments of native objects + "no-new": 1, // disallow use of new operator when not part of the assignment or comparison + "no-new-func": 2, // disallow use of new operator for Function object + "no-new-wrappers": 1, // disallows creating new instances of String,Number, and Boolean + "no-octal": 1, // disallow use of octal literals + "no-octal-escape": 1, // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251"; + "no-proto": 1, // disallow usage of __proto__ property + "no-redeclare": 0, // disallow declaring the same variable more then once + "no-return-assign": 1, // disallow use of assignment in return statement + "no-script-url": 1, // disallow use of javascript: urls. + "no-self-compare": 1, // disallow comparisons where both sides are exactly the same (off by default) + "no-sequences": 1, // disallow use of comma operator + "no-unused-expressions": 0, // disallow usage of expressions in statement position + "no-void": 1, // disallow use of void operator (off by default) + "no-warning-comments": 0, // disallow usage of configurable warning terms in comments": 1, // e.g. TODO or FIXME (off by default) + "no-with": 1, // disallow use of the with statement + radix: 1, // require use of the second argument for parseInt() (off by default) + "semi-spacing": 1, // require a space after a semi-colon + "vars-on-top": 0, // requires to declare all vars on top of their containing scope (off by default) + "wrap-iife": 0, // require immediate function invocation to be wrapped in parentheses (off by default) + yoda: 1, // require or disallow Yoda conditions + + // Variables + // These rules have to do with variable declarations. + + "no-catch-shadow": 1, // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment) + "no-delete-var": 1, // disallow deletion of variables + "no-label-var": 1, // disallow labels that share a name with a variable + "no-shadow": 1, // disallow declaration of variables already declared in the outer scope + "no-shadow-restricted-names": 1, // disallow shadowing of names such as arguments + "no-undef": 2, // disallow use of undeclared variables unless mentioned in a /*global */ block + "no-undefined": 0, // disallow use of undefined variable (off by default) + "no-undef-init": 1, // disallow use of undefined when initializing variables + "no-unused-vars": [ + 1, + { vars: "all", args: "none", ignoreRestSiblings: true } + ], // disallow declaration of variables that are not used in the code + "no-use-before-define": 0, // disallow use of variables before they are defined + + // Node.js + // These rules are specific to JavaScript running on Node.js. + + "handle-callback-err": 1, // enforces error handling in callbacks (off by default) (on by default in the node environment) + "no-mixed-requires": 1, // disallow mixing regular variable and require declarations (off by default) (on by default in the node environment) + "no-new-require": 1, // disallow use of new operator with the require function (off by default) (on by default in the node environment) + "no-path-concat": 1, // disallow string concatenation with __dirname and __filename (off by default) (on by default in the node environment) + "no-process-exit": 0, // disallow process.exit() (on by default in the node environment) + "no-restricted-modules": 1, // restrict usage of specified node modules (off by default) + "no-sync": 0, // disallow use of synchronous methods (off by default) + + // ESLint Comments Plugin + // The following rules are made available via `eslint-plugin-eslint-comments` + "eslint-comments/no-aggregating-enable": 1, // disallows eslint-enable comments for multiple eslint-disable comments + "eslint-comments/no-unlimited-disable": 1, // disallows eslint-disable comments without rule names + "eslint-comments/no-unused-disable": 1, // disallow disables that don't cover any errors + "eslint-comments/no-unused-enable": 1, // // disallow enables that don't enable anything or enable rules that weren't disabled + + // Flow Plugin + // The following rules are made available via `eslint-plugin-flowtype` + "flowtype/define-flow-type": 1, + "flowtype/use-flow-type": 1, + + // Prettier Plugin + // https://github.com/prettier/eslint-plugin-prettier + "prettier/prettier": [2], + + // Stylistic Issues + // These rules are purely matters of style and are quite subjective. + + "key-spacing": 0, + "keyword-spacing": 1, // enforce spacing before and after keywords + "jsx-quotes": [1, "prefer-double"], // enforces the usage of double quotes for all JSX attribute values which doesn’t contain a double quote + "comma-spacing": 0, + "no-multi-spaces": 0, + "brace-style": 0, // enforce one true brace style (off by default) + camelcase: 0, // require camel case names + "consistent-this": 1, // enforces consistent naming when capturing the current execution context (off by default) + "eol-last": 1, // enforce newline at the end of file, with no multiple empty lines + "func-names": 0, // require function expressions to have a name (off by default) + "func-style": 0, // enforces use of function declarations or expressions (off by default) + "new-cap": 0, // require a capital letter for constructors + "new-parens": 1, // disallow the omission of parentheses when invoking a constructor with no arguments + "no-nested-ternary": 0, // disallow nested ternary expressions (off by default) + "no-array-constructor": 1, // disallow use of the Array constructor + "no-empty-character-class": 1, // disallow the use of empty character classes in regular expressions + "no-lonely-if": 0, // disallow if as the only statement in an else block (off by default) + "no-new-object": 1, // disallow use of the Object constructor + "no-spaced-func": 1, // disallow space between function identifier and application + "no-ternary": 0, // disallow the use of ternary operators (off by default) + "no-trailing-spaces": 1, // disallow trailing whitespace at the end of lines + "no-underscore-dangle": 0, // disallow dangling underscores in identifiers + "no-mixed-spaces-and-tabs": 1, // disallow mixed spaces and tabs for indentation + quotes: [1, "single", "avoid-escape"], // specify whether double or single quotes should be used + "quote-props": 0, // require quotes around object literal property names (off by default) + semi: 1, // require or disallow use of semicolons instead of ASI + "sort-vars": 0, // sort variables within the same declaration block (off by default) + "space-in-brackets": 0, // require or disallow spaces inside brackets (off by default) + "space-in-parens": 0, // require or disallow spaces inside parentheses (off by default) + "space-infix-ops": 1, // require spaces around operators + "space-unary-ops": [1, { words: true, nonwords: false }], // require or disallow spaces before/after unary operators (words on by default, nonwords off by default) + "max-nested-callbacks": 0, // specify the maximum depth callbacks can be nested (off by default) + "one-var": 0, // allow just one var statement per function (off by default) + "wrap-regex": 0, // require regex literals to be wrapped in parentheses (off by default) + + // Legacy + // The following rules are included for compatibility with JSHint and JSLint. While the names of the rules may not match up with the JSHint/JSLint counterpart, the functionality is the same. + + "max-depth": 0, // specify the maximum depth that blocks can be nested (off by default) + "max-len": 0, // specify the maximum length of a line in your program (off by default) + "max-params": 0, // limits the number of parameters that can be used in the function declaration. (off by default) + "max-statements": 0, // specify the maximum number of statement allowed in a function (off by default) + "no-bitwise": 1, // disallow use of bitwise operators (off by default) + "no-plusplus": 0, // disallow use of unary operators, ++ and -- (off by default) + + // React Plugin + // The following rules are made available via `eslint-plugin-react`. + + "react/display-name": 0, + "react/jsx-boolean-value": 0, + "react/jsx-no-comment-textnodes": 1, + "react/jsx-no-duplicate-props": 2, + "react/jsx-no-undef": 2, + "react/jsx-sort-props": 0, + "react/jsx-uses-react": 1, + "react/jsx-uses-vars": 1, + "react/no-did-mount-set-state": 1, + "react/no-did-update-set-state": 1, + "react/no-multi-comp": 0, + "react/no-string-refs": 1, + "react/no-unknown-property": 0, + "react/prop-types": 0, + "react/react-in-jsx-scope": 1, + "react/self-closing-comp": 1, + "react/wrap-multilines": 0, + + // React-Hooks Plugin + // The following rules are made available via `eslint-plugin-react-hooks` + "react-hooks/rules-of-hooks": "error", + + // React-Native Plugin + // The following rules are made available via `eslint-plugin-react-native` + + "react-native/no-inline-styles": 1, + + // Jest Plugin + // The following rules are made available via `eslint-plugin-jest`. + "jest/no-disabled-tests": 1, + "jest/no-focused-tests": 1, + "jest/no-identical-title": 1, + "jest/valid-expect": 1 + }, + + overrides: [ + { + files: [ + "**/__fixtures__/**/*.js", + "**/__mocks__/**/*.js", + "**/__tests__/**/*.js", + "jest/**/*.js", + "RNTester/**/*.js" + ], + globals: { + // Expose some Jest globals for test helpers + afterAll: true, + afterEach: true, + beforeAll: true, + beforeEach: true, + expect: true, + jest: true + } + }, + { + files: ["**/__tests__/**/*-test.js"], + env: { + jasmine: true, + jest: true + } + } + ], + + settings: { + react: { + version: "detect" + } + } +}; diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..967e6b3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,29 @@ +--- +name: 🐛 Report a bug +about: Report a reproducible or regression bug.' +labels: 'bug' +--- + +## Environment + + + +## Platforms + + + +## Versions + +- Android: +- iOS: +- react-native-netinfo: +- react-native: +- react: + +## Description + + + +## Reproducible Demo + + diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..08ee7f4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,14 @@ +--- +name: ✨ Feature request +about: Suggest an idea. +labels: 'enhancement' +--- + +## Describe the Feature + + +## Possible Implementations + + +## Related Issues + \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 0000000..dceea01 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,8 @@ +--- +name: 💬 Question +about: You need help with the library. +labels: 'question' +--- + +## Ask your Question + diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..8e1b4bc --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,7 @@ +# Overview + + + + +# Test Plan + diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..37b736c --- /dev/null +++ b/.npmignore @@ -0,0 +1,86 @@ +# JS +node_modules +yarn.lock + +# Project files +CONTRIBUTING.md +CODE_OF_CONDUCT.md +README.md + +# Config files +.babelrc +babel.config.js +.editorconfig +.eslintrc +.flowconfig +.watchmanconfig +jsconfig.json +.npmrc +.gitattributes +.circleci +*.coverage.json +.opensource +.circleci +.eslintignore +codecov.yml + +# Example +example/ + +# Android +android/*/build/ +android/gradlew +android/build +android/gradlew.bat +android/gradle/ +android/com_crashlytics_export_strings.xml +android/local.properties +android/.gradle/ +android/.signing/ +android/.idea/gradle.xml +android/.idea/libraries/ +android/.idea/workspace.xml +android/.idea/tasks.xml +android/.idea/.name +android/.idea/compiler.xml +android/.idea/copyright/profiles_settings.xml +android/.idea/encodings.xml +android/.idea/misc.xml +android/.idea/modules.xml +android/.idea/scopes/scope_settings.xml +android/.idea/vcs.xml +android/*.iml +android/.settings + +# iOS +ios/*.xcodeproj/xcuserdata +*.pbxuser +*.mode1v3 +*.mode2v3 +*.perspectivev3 +*.xcuserstate +project.xcworkspace/ +xcuserdata/ + +# Misc +.DS_Store +.DS_Store? +*.DS_Store +coverage.android.json +coverage.ios.json +coverage +npm-debug.log +.github +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.dbandroid/gradle +docs +.idea +tests/ +bin/test.js +codorials +.vscode +.nyc_output +.tmp diff --git a/.releaserc b/.releaserc new file mode 100644 index 0000000..4a206d3 --- /dev/null +++ b/.releaserc @@ -0,0 +1,15 @@ +{ + "plugins": [ + "@semantic-release/commit-analyzer", + "@semantic-release/release-notes-generator", + "@semantic-release/npm", + "@semantic-release/github", + [ + "@semantic-release/git", + { + "assets": "package.json", + "message": "chore(release): ${nextRelease.version} [skip ci] \n\n${nextRelease.notes}" + } + ] + ] +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b99a5ed --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,51 @@ +# Contributing to React Native Clipboard + +## Development Process +All work on React Native NetInfo happens directly on GitHub. Contributors send pull requests which go through a review process. + +> **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://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github). + +1. Fork the repo and create your branch from `master` (a guide on [how to fork a repository](https://help.github.com/articles/fork-a-repo/)). +2. Run `yarn` or `npm install` to install all required dependencies. +3. Now you are ready to make your changes! + +## Tests & Verifications +Currently we use `flow` for typechecking, `eslint` with `prettier` for linting and formatting the code, and `jest` for unit testing. We also use `detox` for end-to-end testing. All of these are run on CircleCI for all opened pull requests, but you should use them locally when making changes. + +* `yarn test`: Run all tests and validations. +* `yarn validate:eslint`: Run `eslint`. +* `yarn validate:eslint --fix`: Run `eslint` and automatically fix issues. This is useful for correcting code formatting. +* `yarn validate:flow`: Run `flow` typechecking. +* `yarn validate:typescript`: Run `typescript` typechecking. +* `yarn test:jest`: Run unit tests with `jest`. +* `yarn test:detox::build:`: Build the `debug` or `release` app for end-to-end tests with `detox` on either `android` or `ios`. You need to run this before running the test command and whenever you make changes to the native code. +* `yarn test:detox::test:`: Run the `debug` or `release` end-to-end tests with `detox` on either `android` or `ios`. + +## Sending a pull request +When you're sending a pull request: + +* Prefer small pull requests focused on one change. +* Verify that all tests and validations are passing. +* Follow the pull request template when opening a pull request. + +## Commit message convention +We prefix our commit messages with one of the following to signify the kind of change: + +* **build**: Changes that affect the build system or external dependencies. +* **ci**, **chore**: Changes to our CI configuration files and scripts. +* **docs**: Documentation only changes. +* **feat**: A new feature. +* **fix**: A bug fix. +* **perf**: A code change that improves performance. +* **refactor**: A code change that neither fixes a bug nor adds a feature. +* **style**: Changes that do not affect the meaning of the code. +* **test**: Adding missing tests or correcting existing tests. + +## Release process +We use [Semantic Release](http://semantic-release.org) to automatically release new versions of the library when changes are merged into master. Using the commit message convention described above, it will detect if we need to release a patch, minor, or major version of the library. + +## Reporting issues +You can report issues on our [bug tracker](https://github.com/react-native-community/react-native-netinfo/issues). Please search for existing issues and follow the issue template when opening an issue. + +## License +By contributing to React Native NetInfo, you agree that your contributions will be licensed under the **MIT** license. diff --git a/README.md b/README.md index 56e1bbf..2ecda2a 100644 --- a/README.md +++ b/README.md @@ -1 +1,67 @@ -# react-native-clipboard +# @react-native-clipboard + +## Getting started +Install the library using either Yarn: + +``` +yarn add @react-native-community/react-native-clipboard +``` + +or npm: + +``` +npm install --save @react-native-community/react-native-clipboard +``` + +## Migrating from the core `react-native` module +This module was created when the NetInfo was split out from the core of React Native. To migrate to this module you need to follow the installation instructions above and then change you imports from: + +```javascript +import { Clipboard } from "react-native"; +``` + +to: + +```javascript +import Clipboard from "@react-native-community/react-native-clipboard"; +``` + +## Usage +Start by importing the library: + +```javascript +import Clipboard from "@react-native-community/react-native-clipboard"; + +type Props = $ReadOnly<{||}>; +type State = {| + clipboardContent: string, +|}; + +export default class App extends React.Component { + state = { + clipboardContent: 'The state variable which contains Clipboard Content', + }; + + readFromClipboard = async () => { + const content = await Clipboard.getString(); + this.setState({clipboardContent: content}); + }; + + writeToClipboard = async () => { + Clipboard.setString(this.state.text); + alert('Copied to clipboard'); + }; +} +``` + +## Maintainers + +* [M.Haris Baig](https://github.com/harisbaig100) + +## Contributing + +Please see the [`contributing guide`](/CONTRIBUTING.md). + +## License + +The library is released under the MIT licence. For more information see [`LICENSE`](/LICENSE). diff --git a/android/.project b/android/.project new file mode 100644 index 0000000..3964dd3 --- /dev/null +++ b/android/.project @@ -0,0 +1,17 @@ + + + android + Project android created by Buildship. + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + + org.eclipse.buildship.core.gradleprojectnature + + diff --git a/android/src/main/java/com/reactnativecommunity/clipboard/ClipboardModuleTest.java b/android/src/main/java/com/reactnativecommunity/clipboard/ClipboardModuleTest.java new file mode 100644 index 0000000..aa8fc48 --- /dev/null +++ b/android/src/main/java/com/reactnativecommunity/clipboard/ClipboardModuleTest.java @@ -0,0 +1,59 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.modules.clipboard; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.text.ClipboardManager; + +import com.facebook.react.bridge.ReactTestHelper; +import com.facebook.react.modules.clipboard.ClipboardModule; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; + +@SuppressLint({"ClipboardManager", "DeprecatedClass"}) +@RunWith(RobolectricTestRunner.class) +@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) +public class ClipboardModuleTest { + + private static final String TEST_CONTENT = "test"; + + private ClipboardModule mClipboardModule; + private ClipboardManager mClipboardManager; + + @Before + public void setUp() { + mClipboardModule = new ClipboardModule(RuntimeEnvironment.application); + mClipboardManager = + (ClipboardManager) RuntimeEnvironment.application.getSystemService(Context.CLIPBOARD_SERVICE); + } + + @Test + public void testSetString() { + mClipboardModule.setString(TEST_CONTENT); + assertTrue(mClipboardManager.getText().equals(TEST_CONTENT)); + + mClipboardModule.setString(null); + assertFalse(mClipboardManager.hasText()); + + mClipboardModule.setString(""); + assertFalse(mClipboardManager.hasText()); + + mClipboardModule.setString(" "); + assertTrue(mClipboardManager.hasText()); + } +} diff --git a/android/src/main/java/com/reactnativecommunity/clipboard/MainReactPackage.java b/android/src/main/java/com/reactnativecommunity/clipboard/MainReactPackage.java new file mode 100644 index 0000000..31a871d --- /dev/null +++ b/android/src/main/java/com/reactnativecommunity/clipboard/MainReactPackage.java @@ -0,0 +1,373 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.shell; + +import com.facebook.react.LazyReactPackage; +import com.facebook.react.animated.NativeAnimatedModule; +import com.facebook.react.bridge.ModuleSpec; +import com.facebook.react.bridge.NativeModule; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.module.annotations.ReactModuleList; +import com.facebook.react.module.model.ReactModuleInfoProvider; +import com.facebook.react.modules.accessibilityinfo.AccessibilityInfoModule; +import com.facebook.react.modules.appstate.AppStateModule; +import com.facebook.react.modules.blob.BlobModule; +import com.facebook.react.modules.blob.FileReaderModule; +import com.facebook.react.modules.camera.CameraRollManager; +import com.facebook.react.modules.camera.ImageEditingManager; +import com.facebook.react.modules.camera.ImageStoreManager; +import com.facebook.react.modules.clipboard.ClipboardModule; +import com.facebook.react.modules.datepicker.DatePickerDialogModule; +import com.facebook.react.modules.dialog.DialogModule; +import com.facebook.react.modules.fresco.FrescoModule; +import com.facebook.react.modules.i18nmanager.I18nManagerModule; +import com.facebook.react.modules.image.ImageLoaderModule; +import com.facebook.react.modules.intent.IntentModule; +import com.facebook.react.modules.location.LocationModule; +import com.facebook.react.modules.netinfo.NetInfoModule; +import com.facebook.react.modules.network.NetworkingModule; +import com.facebook.react.modules.permissions.PermissionsModule; +import com.facebook.react.modules.share.ShareModule; +import com.facebook.react.modules.statusbar.StatusBarModule; +import com.facebook.react.modules.storage.AsyncStorageModule; +import com.facebook.react.modules.timepicker.TimePickerDialogModule; +import com.facebook.react.modules.toast.ToastModule; +import com.facebook.react.modules.vibration.VibrationModule; +import com.facebook.react.modules.websocket.WebSocketModule; +import com.facebook.react.uimanager.ViewManager; +import com.facebook.react.views.art.ARTRenderableViewManager; +import com.facebook.react.views.art.ARTSurfaceViewManager; +import com.facebook.react.views.checkbox.ReactCheckBoxManager; +import com.facebook.react.views.drawer.ReactDrawerLayoutManager; +import com.facebook.react.views.image.ReactImageManager; +import com.facebook.react.views.modal.ReactModalHostManager; +import com.facebook.react.views.picker.ReactDialogPickerManager; +import com.facebook.react.views.picker.ReactDropdownPickerManager; +import com.facebook.react.views.progressbar.ReactProgressBarViewManager; +import com.facebook.react.views.scroll.ReactHorizontalScrollContainerViewManager; +import com.facebook.react.views.scroll.ReactHorizontalScrollViewManager; +import com.facebook.react.views.scroll.ReactScrollViewManager; +import com.facebook.react.views.slider.ReactSliderManager; +import com.facebook.react.views.swiperefresh.SwipeRefreshLayoutManager; +import com.facebook.react.views.switchview.ReactSwitchManager; +import com.facebook.react.views.text.ReactRawTextManager; +import com.facebook.react.views.text.ReactTextViewManager; +import com.facebook.react.views.text.ReactVirtualTextViewManager; +import com.facebook.react.views.text.frescosupport.FrescoBasedReactTextInlineImageViewManager; +import com.facebook.react.views.textinput.ReactTextInputManager; +import com.facebook.react.views.toolbar.ReactToolbarManager; +import com.facebook.react.views.view.ReactViewManager; +import com.facebook.react.views.viewpager.ReactViewPagerManager; +import com.facebook.react.views.webview.ReactWebViewManager; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import javax.inject.Provider; + +/** + * Package defining basic modules and view managers. + */ +@ReactModuleList(nativeModules = { + AccessibilityInfoModule.class, + AppStateModule.class, + BlobModule.class, + FileReaderModule.class, + AsyncStorageModule.class, + CameraRollManager.class, + ClipboardModule.class, + DatePickerDialogModule.class, + DialogModule.class, + FrescoModule.class, + I18nManagerModule.class, + ImageEditingManager.class, + ImageLoaderModule.class, + ImageStoreManager.class, + IntentModule.class, + LocationModule.class, + NativeAnimatedModule.class, + NetworkingModule.class, + NetInfoModule.class, + PermissionsModule.class, + ShareModule.class, + StatusBarModule.class, + TimePickerDialogModule.class, + ToastModule.class, + VibrationModule.class, + WebSocketModule.class, + +}) +public class MainReactPackage extends LazyReactPackage { + + private MainPackageConfig mConfig; + + public MainReactPackage() { + } + + /** + * Create a new package with configuration + */ + public MainReactPackage(MainPackageConfig config) { + mConfig = config; + } + + @Override + public List getNativeModules(final ReactApplicationContext context) { + return Arrays.asList( + ModuleSpec.nativeModuleSpec( + AccessibilityInfoModule.class, + new Provider() { + @Override + public NativeModule get() { + return new AccessibilityInfoModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + AppStateModule.class, + new Provider() { + @Override + public NativeModule get() { + return new AppStateModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + BlobModule.class, + new Provider() { + @Override + public NativeModule get() { + return new BlobModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + FileReaderModule.class, + new Provider() { + @Override + public NativeModule get() { + return new FileReaderModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + AsyncStorageModule.class, + new Provider() { + @Override + public NativeModule get() { + return new AsyncStorageModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + CameraRollManager.class, + new Provider() { + @Override + public NativeModule get() { + return new CameraRollManager(context); + } + }), + ModuleSpec.nativeModuleSpec( + ClipboardModule.class, + new Provider() { + @Override + public NativeModule get() { + return new ClipboardModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + DatePickerDialogModule.class, + new Provider() { + @Override + public NativeModule get() { + return new DatePickerDialogModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + DialogModule.class, + new Provider() { + @Override + public NativeModule get() { + return new DialogModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + FrescoModule.class, + new Provider() { + @Override + public NativeModule get() { + return new FrescoModule( + context, true, mConfig != null ? mConfig.getFrescoConfig() : null); + } + }), + ModuleSpec.nativeModuleSpec( + I18nManagerModule.class, + new Provider() { + @Override + public NativeModule get() { + return new I18nManagerModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + ImageEditingManager.class, + new Provider() { + @Override + public NativeModule get() { + return new ImageEditingManager(context); + } + }), + ModuleSpec.nativeModuleSpec( + ImageLoaderModule.class, + new Provider() { + @Override + public NativeModule get() { + return new ImageLoaderModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + ImageStoreManager.class, + new Provider() { + @Override + public NativeModule get() { + return new ImageStoreManager(context); + } + }), + ModuleSpec.nativeModuleSpec( + IntentModule.class, + new Provider() { + @Override + public NativeModule get() { + return new IntentModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + LocationModule.class, + new Provider() { + @Override + public NativeModule get() { + return new LocationModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + NativeAnimatedModule.class, + new Provider() { + @Override + public NativeModule get() { + return new NativeAnimatedModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + NetworkingModule.class, + new Provider() { + @Override + public NativeModule get() { + return new NetworkingModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + NetInfoModule.class, + new Provider() { + @Override + public NativeModule get() { + return new NetInfoModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + PermissionsModule.class, + new Provider() { + @Override + public NativeModule get() { + return new PermissionsModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + ShareModule.class, + new Provider() { + @Override + public NativeModule get() { + return new ShareModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + StatusBarModule.class, + new Provider() { + @Override + public NativeModule get() { + return new StatusBarModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + TimePickerDialogModule.class, + new Provider() { + @Override + public NativeModule get() { + return new TimePickerDialogModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + ToastModule.class, + new Provider() { + @Override + public NativeModule get() { + return new ToastModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + VibrationModule.class, + new Provider() { + @Override + public NativeModule get() { + return new VibrationModule(context); + } + }), + ModuleSpec.nativeModuleSpec( + WebSocketModule.class, + new Provider() { + @Override + public NativeModule get() { + return new WebSocketModule(context); + } + })); + } + + @Override + public List createViewManagers(ReactApplicationContext reactContext) { + List viewManagers = new ArrayList<>(); + + viewManagers.add(ARTRenderableViewManager.createARTGroupViewManager()); + viewManagers.add(ARTRenderableViewManager.createARTShapeViewManager()); + viewManagers.add(ARTRenderableViewManager.createARTTextViewManager()); + viewManagers.add(new ReactCheckBoxManager()); + viewManagers.add(new ReactDialogPickerManager()); + viewManagers.add(new ReactDrawerLayoutManager()); + viewManagers.add(new ReactDropdownPickerManager()); + viewManagers.add(new ReactHorizontalScrollViewManager()); + viewManagers.add(new ReactHorizontalScrollContainerViewManager()); + viewManagers.add(new ReactProgressBarViewManager()); + viewManagers.add(new ReactScrollViewManager()); + viewManagers.add(new ReactSliderManager()); + viewManagers.add(new ReactSwitchManager()); + viewManagers.add(new ReactToolbarManager()); + viewManagers.add(new ReactWebViewManager()); + viewManagers.add(new SwipeRefreshLayoutManager()); + + // Native equivalents + viewManagers.add(new ARTSurfaceViewManager()); + viewManagers.add(new FrescoBasedReactTextInlineImageViewManager()); + viewManagers.add(new ReactImageManager()); + viewManagers.add(new ReactModalHostManager()); + viewManagers.add(new ReactRawTextManager()); + viewManagers.add(new ReactTextInputManager()); + viewManagers.add(new ReactTextViewManager()); + viewManagers.add(new ReactViewManager()); + viewManagers.add(new ReactViewPagerManager()); + viewManagers.add(new ReactVirtualTextViewManager()); + + return viewManagers; + } + + @Override + public ReactModuleInfoProvider getReactModuleInfoProvider() { + // This has to be done via reflection or we break open source. + return LazyReactPackage.getReactModuleInfoProviderViaReflection(this); + } +} diff --git a/android/src/main/java/com/reactnativecommunity/clipboard/RedBoxDialog.java b/android/src/main/java/com/reactnativecommunity/clipboard/RedBoxDialog.java new file mode 100644 index 0000000..5618a07 --- /dev/null +++ b/android/src/main/java/com/reactnativecommunity/clipboard/RedBoxDialog.java @@ -0,0 +1,354 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.devsupport; + +import javax.annotation.Nullable; + +import android.app.Dialog; +import android.content.Context; +import android.graphics.Color; +import android.net.Uri; +import android.os.AsyncTask; +import android.text.SpannedString; +import android.text.method.LinkMovementMethod; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.widget.AdapterView; +import android.widget.BaseAdapter; +import android.widget.Button; +import android.widget.ListView; +import android.widget.ProgressBar; +import android.widget.TextView; + +import com.facebook.common.logging.FLog; +import com.facebook.infer.annotation.Assertions; +import com.facebook.react.R; +import com.facebook.react.common.MapBuilder; +import com.facebook.react.common.ReactConstants; +import com.facebook.react.devsupport.interfaces.DevSupportManager; +import com.facebook.react.devsupport.interfaces.StackFrame; +import com.facebook.react.devsupport.RedBoxHandler.ReportCompletedListener; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import org.json.JSONObject; + +/** + * Dialog for displaying JS errors in an eye-catching form (red box). + */ +/* package */ class RedBoxDialog extends Dialog implements AdapterView.OnItemClickListener { + + private final DevSupportManager mDevSupportManager; + private final DoubleTapReloadRecognizer mDoubleTapReloadRecognizer; + private final @Nullable RedBoxHandler mRedBoxHandler; + + private ListView mStackView; + private Button mReloadJsButton; + private Button mDismissButton; + private Button mCopyToClipboardButton; + private @Nullable Button mReportButton; + private @Nullable TextView mReportTextView; + private @Nullable ProgressBar mLoadingIndicator; + private @Nullable View mLineSeparator; + private boolean isReporting = false; + + private ReportCompletedListener mReportCompletedListener = new ReportCompletedListener() { + @Override + public void onReportSuccess(final SpannedString spannedString) { + isReporting = false; + Assertions.assertNotNull(mReportButton).setEnabled(true); + Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.GONE); + Assertions.assertNotNull(mReportTextView).setText(spannedString); + } + @Override + public void onReportError(final SpannedString spannedString) { + isReporting = false; + Assertions.assertNotNull(mReportButton).setEnabled(true); + Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.GONE); + Assertions.assertNotNull(mReportTextView).setText(spannedString); + } + }; + + private View.OnClickListener mReportButtonOnClickListener = new View.OnClickListener() { + @Override + public void onClick(View view) { + if (mRedBoxHandler == null || !mRedBoxHandler.isReportEnabled() || isReporting) { + return; + } + isReporting = true; + Assertions.assertNotNull(mReportTextView).setText("Reporting..."); + Assertions.assertNotNull(mReportTextView).setVisibility(View.VISIBLE); + Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.VISIBLE); + Assertions.assertNotNull(mLineSeparator).setVisibility(View.VISIBLE); + Assertions.assertNotNull(mReportButton).setEnabled(false); + + String title = Assertions.assertNotNull(mDevSupportManager.getLastErrorTitle()); + StackFrame[] stack = Assertions.assertNotNull(mDevSupportManager.getLastErrorStack()); + String sourceUrl = mDevSupportManager.getSourceUrl(); + + mRedBoxHandler.reportRedbox( + view.getContext(), + title, + stack, + sourceUrl, + Assertions.assertNotNull(mReportCompletedListener)); + } + }; + + private static class StackAdapter extends BaseAdapter { + private static final int VIEW_TYPE_COUNT = 2; + private static final int VIEW_TYPE_TITLE = 0; + private static final int VIEW_TYPE_STACKFRAME = 1; + + private final String mTitle; + private final StackFrame[] mStack; + + private static class FrameViewHolder { + private final TextView mMethodView; + private final TextView mFileView; + + private FrameViewHolder(View v) { + mMethodView = (TextView) v.findViewById(R.id.rn_frame_method); + mFileView = (TextView) v.findViewById(R.id.rn_frame_file); + } + } + + public StackAdapter(String title, StackFrame[] stack) { + mTitle = title; + mStack = stack; + } + + @Override + public boolean areAllItemsEnabled() { + return false; + } + + @Override + public boolean isEnabled(int position) { + return position > 0; + } + + @Override + public int getCount() { + return mStack.length + 1; + } + + @Override + public Object getItem(int position) { + return position == 0 ? mTitle : mStack[position - 1]; + } + + @Override + public long getItemId(int position) { + return position; + } + + @Override + public int getViewTypeCount() { + return VIEW_TYPE_COUNT; + } + + @Override + public int getItemViewType(int position) { + return position == 0 ? VIEW_TYPE_TITLE : VIEW_TYPE_STACKFRAME; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + if (position == 0) { + TextView title = convertView != null + ? (TextView) convertView + : (TextView) LayoutInflater.from(parent.getContext()) + .inflate(R.layout.redbox_item_title, parent, false); + title.setText(mTitle); + return title; + } else { + if (convertView == null) { + convertView = LayoutInflater.from(parent.getContext()) + .inflate(R.layout.redbox_item_frame, parent, false); + convertView.setTag(new FrameViewHolder(convertView)); + } + StackFrame frame = mStack[position - 1]; + FrameViewHolder holder = (FrameViewHolder) convertView.getTag(); + holder.mMethodView.setText(frame.getMethod()); + holder.mFileView.setText(StackTraceHelper.formatFrameSource(frame)); + return convertView; + } + } + } + + private static class OpenStackFrameTask extends AsyncTask { + private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + + private final DevSupportManager mDevSupportManager; + + private OpenStackFrameTask(DevSupportManager devSupportManager) { + mDevSupportManager = devSupportManager; + } + + @Override + protected Void doInBackground(StackFrame... stackFrames) { + try { + String openStackFrameUrl = + Uri.parse(mDevSupportManager.getSourceUrl()).buildUpon() + .path("/open-stack-frame") + .query(null) + .build() + .toString(); + OkHttpClient client = new OkHttpClient(); + for (StackFrame frame: stackFrames) { + String payload = stackFrameToJson(frame).toString(); + RequestBody body = RequestBody.create(JSON, payload); + Request request = new Request.Builder().url(openStackFrameUrl).post(body).build(); + client.newCall(request).execute(); + } + } catch (Exception e) { + FLog.e(ReactConstants.TAG, "Could not open stack frame", e); + } + return null; + } + + private static JSONObject stackFrameToJson(StackFrame frame) { + return new JSONObject( + MapBuilder.of( + "file", frame.getFile(), + "methodName", frame.getMethod(), + "lineNumber", frame.getLine(), + "column", frame.getColumn() + )); + } + } + + private static class CopyToHostClipBoardTask extends AsyncTask { + private final DevSupportManager mDevSupportManager; + + private CopyToHostClipBoardTask(DevSupportManager devSupportManager) { + mDevSupportManager = devSupportManager; + } + + @Override + protected Void doInBackground(String... clipBoardString) { + try { + String sendClipBoardUrl = + Uri.parse(mDevSupportManager.getSourceUrl()).buildUpon() + .path("/copy-to-clipboard") + .query(null) + .build() + .toString(); + for (String string: clipBoardString) { + OkHttpClient client = new OkHttpClient(); + RequestBody body = RequestBody.create(null, string); + Request request = new Request.Builder().url(sendClipBoardUrl).post(body).build(); + client.newCall(request).execute(); + } + } catch (Exception e) { + FLog.e(ReactConstants.TAG, "Could not copy to the host clipboard", e); + } + return null; + } + } + + protected RedBoxDialog( + Context context, + DevSupportManager devSupportManager, + @Nullable RedBoxHandler redBoxHandler) { + super(context, R.style.Theme_Catalyst_RedBox); + + requestWindowFeature(Window.FEATURE_NO_TITLE); + + setContentView(R.layout.redbox_view); + + mDevSupportManager = devSupportManager; + mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer(); + mRedBoxHandler = redBoxHandler; + + mStackView = (ListView) findViewById(R.id.rn_redbox_stack); + mStackView.setOnItemClickListener(this); + + mReloadJsButton = (Button) findViewById(R.id.rn_redbox_reload_button); + mReloadJsButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + mDevSupportManager.handleReloadJS(); + } + }); + mDismissButton = (Button) findViewById(R.id.rn_redbox_dismiss_button); + mDismissButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + dismiss(); + } + }); + mCopyToClipboardButton = (Button) findViewById(R.id.rn_redbox_copy_button); + mCopyToClipboardButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + String title = mDevSupportManager.getLastErrorTitle(); + StackFrame[] stack = mDevSupportManager.getLastErrorStack(); + Assertions.assertNotNull(title); + Assertions.assertNotNull(stack); + new CopyToHostClipBoardTask(mDevSupportManager).executeOnExecutor( + AsyncTask.THREAD_POOL_EXECUTOR, + StackTraceHelper.formatStackTrace(title, stack)); + } + }); + + if (mRedBoxHandler != null && mRedBoxHandler.isReportEnabled()) { + mLoadingIndicator = (ProgressBar) findViewById(R.id.rn_redbox_loading_indicator); + mLineSeparator = (View) findViewById(R.id.rn_redbox_line_separator); + mReportTextView = (TextView) findViewById(R.id.rn_redbox_report_label); + mReportTextView.setMovementMethod(LinkMovementMethod.getInstance()); + mReportTextView.setHighlightColor(Color.TRANSPARENT); + mReportButton = (Button) findViewById(R.id.rn_redbox_report_button); + mReportButton.setOnClickListener(mReportButtonOnClickListener); + } + } + + public void setExceptionDetails(String title, StackFrame[] stack) { + mStackView.setAdapter(new StackAdapter(title, stack)); + } + + /** + * Show the report button, hide the report textview and the loading indicator. + */ + public void resetReporting() { + if (mRedBoxHandler == null || !mRedBoxHandler.isReportEnabled()) { + return; + } + isReporting = false; + Assertions.assertNotNull(mReportTextView).setVisibility(View.GONE); + Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.GONE); + Assertions.assertNotNull(mLineSeparator).setVisibility(View.GONE); + Assertions.assertNotNull(mReportButton).setVisibility(View.VISIBLE); + Assertions.assertNotNull(mReportButton).setEnabled(true); + } + + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + new OpenStackFrameTask(mDevSupportManager).executeOnExecutor( + AsyncTask.THREAD_POOL_EXECUTOR, + (StackFrame) mStackView.getAdapter().getItem(position)); + } + + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_MENU) { + mDevSupportManager.showDevOptionsDialog(); + return true; + } + if (mDoubleTapReloadRecognizer.didDoubleTapR(keyCode, getCurrentFocus())) { + mDevSupportManager.handleReloadJS(); + } + return super.onKeyUp(keyCode, event); + } +} diff --git a/babel.config.js b/babel.config.js index 62248ca..ab1f150 100644 --- a/babel.config.js +++ b/babel.config.js @@ -5,7 +5,7 @@ module.exports = { "module-resolver", { alias: { - "@react-native-community/viewpager": "./js" + "@react-native-community/react-native-clipboard": "./js" }, cwd: "babelrc" } diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 0000000..a62752d --- /dev/null +++ b/example/.gitignore @@ -0,0 +1,7 @@ +node_modules/**/* +.expo/* +npm-debug.* +*.jks +*.p12 +*.key +*.mobileprovision diff --git a/example/.watchmanconfig b/example/.watchmanconfig new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/example/.watchmanconfig @@ -0,0 +1 @@ +{} diff --git a/example/App.js b/example/App.js new file mode 100644 index 0000000..bade2be --- /dev/null +++ b/example/App.js @@ -0,0 +1,82 @@ +import React from 'react'; +import { StyleSheet, Text, View, Button, TextInput } from 'react-native'; +import Clipboard from "@react-native-community/react-native-clipboard"; + +type Props = $ReadOnly<{||}>; +type State = {| + text: string, + clipboardContent: string, +|}; + +export default class App extends React.Component { + state = { + text: '', + clipboardContent: 'Click down to see whats in Clipboard', + }; + + readFromClipboard = async () => { + const content = await Clipboard.getString(); + this.setState({clipboardContent: content}); + }; + + writeToClipboard = async () => { + Clipboard.setString(this.state.text); + alert('Copied to clipboard'); + }; + + render() { + return ( + + + Clipboard Contents: + {this.state.clipboardContent} + +