├── .babelrc
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── README.md
├── examples
└── basic
│ ├── .babelrc
│ ├── .flowconfig
│ ├── .gitignore
│ ├── .watchmanconfig
│ ├── App.js
│ ├── README.md
│ ├── app.json
│ ├── package.json
│ └── yarn.lock
├── package.json
├── packages
└── react-native-menu
│ ├── LICENSE
│ ├── README.md
│ ├── android.demo.gif
│ ├── ios.demo.gif
│ ├── package.json
│ ├── src
│ ├── index.js
│ └── menu
│ │ ├── MenuContext.test.js
│ │ ├── __snapshots__
│ │ └── MenuContext.test.js.snap
│ │ ├── index.js
│ │ ├── makeAnimatedOptionsContainer.js
│ │ ├── makeMenu.js
│ │ ├── makeMenuContext.js
│ │ ├── makeMenuOption.js
│ │ ├── makeMenuOptions.js
│ │ ├── makeMenuTrigger.js
│ │ ├── makeModel.js
│ │ └── makeStyles.js
│ └── test
│ ├── integration
│ └── menu-tests.js
│ └── support
│ ├── appium-servers.js
│ ├── apps.js
│ ├── caps.js
│ └── setup.js
└── yarn.lock
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [ "env", "react-native" ]
3 | }
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | node_modules/
5 |
6 | # testing
7 | coverage/
8 |
9 | # production
10 | es/
11 | lib/
12 | umd/
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 | lerna-debug.log*
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ### 0.19.0
2 |
3 | - Fixes a performance issue where registering menu options on already
4 | rendered and opened menu causes infinite render loop (Closes #5, #9).
5 |
6 | ### 0.18.11
7 |
8 | - Adds method to `MenuContext` to check if the menu is opened or not.
9 | - Supports re-rendering of `MenuOptions` while the menu is opened.
10 |
11 | ### 0.18.10
12 |
13 | - Adds callback for `Menu` component when menu opens and closes.
14 | - Allows menu options to re-render dynamically while menu is open.
15 |
16 | ### 0.18.9
17 |
18 | - Adds more customization options for options container.
19 | - Fixes issue with wrong positioning calculation.
20 |
21 | ### 0.18.6
22 |
23 | - Dropdown menu now animates in (using scale animation) instead of just appearing.
24 | - Fixes opacity issue with backdrop for iOS.
25 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, gender identity and expression, level of experience,
9 | nationality, personal appearance, race, religion, or sexual identity and
10 | orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at jack.hsu@gmail.com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at [http://contributor-covenant.org/version/1/4][version]
72 |
73 | [homepage]: http://contributor-covenant.org
74 | [version]: http://contributor-covenant.org/version/1/4/
75 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://www.npmjs.com/package/react-native-menu)
2 |
3 | # react-native-menu
4 |
5 | A menu component for Android and iOS that provides a dropdown similar to Android's
6 | [Spinner](http://developer.android.com/reference/android/widget/Spinner.html), but does not
7 | retain a persistent selection.
8 |
9 | The API is very flexible so you are free to extend the styling and behaviour.
10 |
11 | ## Installation
12 |
13 | ```
14 | $ npm install react-native-menu --save
15 | ```
16 |
17 | Or with yarn:
18 |
19 | ```
20 | $ yarn add react-native-menu
21 | ```
22 |
23 | ## Demo
24 |
25 | | iOS | Android |
26 | | --- | ------- |
27 | |  |  |
28 |
29 | ## Basic Usage
30 |
31 | ```js
32 | import React, { View, Text, AppRegistry } from 'react-native';
33 | import Menu, { MenuContext, MenuOptions, MenuOption, MenuTrigger } from 'react-native-menu';
34 |
35 | const App = () => (
36 | // You need to place a MenuContext somewhere in your application, usually at the root.
37 | // Menus will open within the context, and only one menu can open at a time per context.
38 |
39 |
40 | Hello!
41 |
42 | );
43 |
44 | const TopNavigation = () => (
45 |
46 | My App
47 |
60 |
61 | );
62 |
63 | AppRegistry.registerComponent('Example', () => App);
64 | ```
65 |
66 | **Important:** In order for the `
` to work, you need to mount `` as an ancestor to ``. This allows
67 | the menu to open on top of all other components mounted under `` -- basically, the menu will be moved
68 | to be the last child of the context.
69 |
70 | You must also have a `` and a `` as direct children under ``. The `MenuTrigger` component
71 | opens the menu when pressed. The `MenuOptions` component can take *any* children, but you need at least one `MenuOption`
72 | child in order for the menu to actually do anything.
73 |
74 | The `MenuOption` component can take *any* children.
75 |
76 | Please refer to the full working example [here](./Example/Example.js).
77 |
78 | ### Adding feedback to `MenuTrigger` and `MenuOption` components
79 | By default, the `MenuTrigger` and `MenuOption` components render with a
80 | `TouchableWithoutFeedback` component, however this may make the menu feel
81 | unnatural in your app.
82 |
83 | To override this, both components will take a `renderTouchable` property, which
84 | should be a function which returns an alternate component to use. For example:
85 |
86 | ```js
87 | import { TouchableOpacity, Text } from 'react-native';
88 | import Menu, { MenuOptions, MenuOption, MenuTrigger } from 'react-native-menu';
89 |
90 | const renderTouchable = () => ;
91 |
92 | const menu = () => (
93 |
106 | );
107 | ```
108 |
109 | ## API
110 |
111 | ### MenuContext
112 |
113 | Methods:
114 |
115 | - isMenuOpen() -- Returns `true` if menu is open
116 | - openMenu() -- Opens the menu
117 | - closeMenu() -- Closes the menu
118 | - toggleMenu() -- Toggle the menu between open and close
119 |
120 | Props:
121 |
122 |
123 | - 'detectBackHandler' -- If true, menu context detects an Android hardware back press, closes menu and stops it from propagating and potentially causing bugs. (Default: true)
124 | - `style` -- Overrides default style properties (user-defined style will take priority)
125 | - `onCloseMenu` -- Handler that will be called with the state of `MenuContext`, if defined.
126 |
127 | ### Menu
128 |
129 | Methods:
130 |
131 | - getName() -- Returns the menu name (e.g. useful to get auto generated name)
132 |
133 | Props:
134 |
135 | - `onSelect` -- This function is called with the value the `MenuOption` that has been selected by the user
136 |
137 | ### MenuTrigger
138 |
139 | Props:
140 |
141 | - `disabled` -- If true, then this trigger is not pressable
142 | - `style` -- Overrides default style properties (user-defined style will take priority)
143 | - `renderTouchable` -- A function which can override the default
144 | `TouchableWithoutFeedback` component by returning a different component. [See
145 | an example here](#adding-feedback-to-menutrigger-and-menuoption-components).
146 |
147 | ### MenuOptions
148 |
149 | Props:
150 |
151 | - `optionsContainerStyle` -- Provides custom styling for options container
152 | - `renderOptionsContainer` -- A function that renders takes in the `MenuOptions` element and renders a container element
153 | that contains the options. Default function wraps options with a `ScrollView`.
154 |
155 | For example, if you want to change the options width to `300`, you can use ``.
156 | To further customize the rendered content you can do something like
157 | ` {options}}>`.
158 |
159 | ### MenuOption
160 |
161 | Props:
162 |
163 | - `disabled` -- If true, then this option is not selectable
164 | - `style` -- Overrides default style properties (user-defined style will take priority)
165 | - `renderTouchable` -- A function which can override the default
166 | `TouchableWithoutFeedback` component by returning a different component. [See
167 | an example here](#adding-feedback-to-menutrigger-and-menuoption-components).
168 |
169 | ## Latest Changes
170 |
171 | ### 0.23.0
172 |
173 | - Compatible with latest react-native version. Thanks to all the people who submitted a PR! ([@amensouissi](https://github.com/amensouissi), [SkipperEl](https://github.com/SkipperEl))
174 |
175 | ### 0.20.1
176 |
177 | - Changed menu elevation as per [material design spec](https://material.google.com/what-is-material/elevation-shadows.html) (thanks [@heydabop](https://github.com/heydabop)!)
178 |
179 | ### 0.20.0
180 |
181 | - Fixes compatibility with React Native 0.27.2 (thanks [@Froelund](https://github.com/Froelund))
182 |
183 | ### 0.19.0
184 |
185 | - Fixes a performance issue where registering menu options on already
186 | rendered and opened menu causes infinite render loop (Closes #5, #9).
187 |
188 | ### 0.18.15
189 |
190 | - Fixes issue where multiple unnamed `Menu` components under one `MenuContext
191 | causes bad positioning.
192 |
193 | ### 0.18.14
194 |
195 | - Lazily calculate menu position on open -- fixes stale calculation issues.
196 |
197 | ## Roadmap
198 |
199 | ### Features
200 |
201 | - Allow positioning of menu to be customized (currently only anchors to top-right of `Menu`).
202 | - Detect if the menu will be rendered off-screen, and adjust positioning accordingly.
203 |
204 | ## Testing
205 |
206 | Install dev modules:
207 |
208 | ```
209 | yarn
210 | ```
211 |
212 | ### Run unit tests
213 |
214 | ```
215 | yarn test:unit
216 | ```
217 |
218 | ### Run integration tests
219 |
220 | Make sure you have a connected android device. You find list devices using `adb devices`.
221 |
222 | ```
223 | yarn test:integration
224 | ```
225 |
226 | ## Contributing
227 |
228 | Contributions are welcome! Just open an issues with any ideas or pull-requests.
229 | I will take a look when I have time. :)
230 |
--------------------------------------------------------------------------------
/examples/basic/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": ["babel-preset-expo"],
3 | "env": {
4 | "development": {
5 | "plugins": ["transform-react-jsx-source"]
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/examples/basic/.flowconfig:
--------------------------------------------------------------------------------
1 | [ignore]
2 | ; We fork some components by platform
3 | .*/*[.]android.js
4 |
5 | ; Ignore "BUCK" generated dirs
6 | /\.buckd/
7 |
8 | ; Ignore unexpected extra "@providesModule"
9 | .*/node_modules/.*/node_modules/fbjs/.*
10 |
11 | ; Ignore duplicate module providers
12 | ; For RN Apps installed via npm, "Libraries" folder is inside
13 | ; "node_modules/react-native" but in the source repo it is in the root
14 | .*/Libraries/react-native/React.js
15 | .*/Libraries/react-native/ReactNative.js
16 |
17 | ; Additional create-react-native-app ignores
18 |
19 | ; Ignore duplicate module providers
20 | .*/node_modules/fbemitter/lib/*
21 |
22 | ; Ignore misbehaving dev-dependencies
23 | .*/node_modules/xdl/build/*
24 | .*/node_modules/reqwest/tests/*
25 |
26 | ; Ignore missing expo-sdk dependencies (temporarily)
27 | ; https://github.com/expo/expo/issues/162
28 | .*/node_modules/expo/src/*
29 |
30 | ; Ignore react-native-fbads dependency of the expo sdk
31 | .*/node_modules/react-native-fbads/*
32 |
33 | [include]
34 |
35 | [libs]
36 | node_modules/react-native/Libraries/react-native/react-native-interface.js
37 | node_modules/react-native/flow
38 | flow/
39 |
40 | [options]
41 | module.system=haste
42 |
43 | emoji=true
44 |
45 | experimental.strict_type_args=true
46 |
47 | munge_underscores=true
48 |
49 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub'
50 |
51 | suppress_type=$FlowIssue
52 | suppress_type=$FlowFixMe
53 | suppress_type=$FixMe
54 |
55 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(4[0-9]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)
56 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(4[0-9]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+
57 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
58 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError
59 |
60 | unsafe.enable_getters_and_setters=true
61 |
62 | [version]
63 | ^0.49.1
64 |
--------------------------------------------------------------------------------
/examples/basic/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | .expo/
3 | npm-debug.*
4 |
--------------------------------------------------------------------------------
/examples/basic/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
2 |
--------------------------------------------------------------------------------
/examples/basic/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { ScrollView, StyleSheet, Text, View } from 'react-native';
3 | import Menu, {
4 | MenuContext,
5 | MenuOptions,
6 | MenuOption,
7 | MenuTrigger
8 | } from 'react-native-menu';
9 |
10 | export default React.createClass({
11 | componentDidMount() {
12 | // We can use the public context API to open/close/toggle the menu.
13 | //setInterval(() => {
14 | // this.refs.MenuContext.toggleMenu('menu1');
15 | //}, 2000);
16 | },
17 | getInitialState() {
18 | return {
19 | message: 'Try clicking the top-right menus',
20 | firstMenuDisabled: false,
21 | dropdownSelection: '-- Choose --'
22 | };
23 | },
24 | setMessage(value) {
25 | if (typeof value === 'string') {
26 | this.setState({ message: `You selected "${value}"` });
27 | } else {
28 | this.setState({ message: `Woah!\n\nYou selected an object:\n\n${JSON.stringify(value)}` });
29 | }
30 | return value !== 'do not close';
31 | },
32 | setFirstMenuDisabled(disabled) {
33 | this.setState({
34 | message: `First menu is ${disabled ? 'disabled' : 'enabled'}`,
35 | firstMenuDisabled: disabled
36 | });
37 | return false;
38 | },
39 | render() {
40 | return (
41 |
42 |
43 |
63 |
64 |
65 |
85 |
86 |
87 |
88 | { this.state.message }
89 |
90 |
91 |
92 |
93 | You can also make it a dropdown
94 |
95 |
118 |
119 |
120 | );
121 | }
122 | });
123 |
124 | const styles = StyleSheet.create({
125 | topbar: {
126 | flexDirection: 'row',
127 | justifyContent: 'flex-end',
128 | backgroundColor: 'black',
129 | paddingHorizontal: 5,
130 | paddingVertical: 10
131 | },
132 | menuTrigger: {
133 | flexDirection: 'row',
134 | paddingHorizontal: 10
135 | },
136 | menuTriggerText: {
137 | color: 'lightgrey',
138 | fontWeight: '600',
139 | fontSize: 20
140 | },
141 | disabled: {
142 | color: '#ccc'
143 | },
144 | divider: {
145 | marginVertical: 5,
146 | marginHorizontal: 2,
147 | borderBottomWidth: 1,
148 | borderColor: '#ccc'
149 | },
150 | content: {
151 | backgroundColor: 'white',
152 | paddingHorizontal: 10,
153 | paddingTop: 20,
154 | paddingBottom: 30,
155 | borderBottomWidth: 1,
156 | borderColor: '#ccc'
157 | },
158 | contentText: {
159 | fontSize: 18
160 | },
161 | dropdown: {
162 | width: 300,
163 | borderColor: '#999',
164 | borderWidth: 1,
165 | padding: 5
166 | },
167 | dropdownOptions: {
168 | marginTop: 30,
169 | borderColor: '#ccc',
170 | borderWidth: 2,
171 | width: 300,
172 | height: 200
173 | }
174 | });
175 |
--------------------------------------------------------------------------------
/examples/basic/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React Native App](https://github.com/react-community/create-react-native-app).
2 |
3 | Below you'll find information about performing common tasks. The most recent version of this guide is available [here](https://github.com/react-community/create-react-native-app/blob/master/react-native-scripts/template/README.md).
4 |
5 | ## Table of Contents
6 |
7 | * [Updating to New Releases](#updating-to-new-releases)
8 | * [Available Scripts](#available-scripts)
9 | * [npm start](#npm-start)
10 | * [npm test](#npm-test)
11 | * [npm run ios](#npm-run-ios)
12 | * [npm run android](#npm-run-android)
13 | * [npm run eject](#npm-run-eject)
14 | * [Writing and Running Tests](#writing-and-running-tests)
15 | * [Environment Variables](#environment-variables)
16 | * [Configuring Packager IP Address](#configuring-packager-ip-address)
17 | * [Adding Flow](#adding-flow)
18 | * [Customizing App Display Name and Icon](#customizing-app-display-name-and-icon)
19 | * [Sharing and Deployment](#sharing-and-deployment)
20 | * [Publishing to Expo's React Native Community](#publishing-to-expos-react-native-community)
21 | * [Building an Expo "standalone" app](#building-an-expo-standalone-app)
22 | * [Ejecting from Create React Native App](#ejecting-from-create-react-native-app)
23 | * [Build Dependencies (Xcode & Android Studio)](#build-dependencies-xcode-android-studio)
24 | * [Should I Use ExpoKit?](#should-i-use-expokit)
25 | * [Troubleshooting](#troubleshooting)
26 | * [Networking](#networking)
27 | * [iOS Simulator won't open](#ios-simulator-wont-open)
28 | * [QR Code does not scan](#qr-code-does-not-scan)
29 |
30 | ## Updating to New Releases
31 |
32 | You should only need to update the global installation of `create-react-native-app` very rarely, ideally never.
33 |
34 | Updating the `react-native-scripts` dependency of your app should be as simple as bumping the version number in `package.json` and reinstalling your project's dependencies.
35 |
36 | Upgrading to a new version of React Native requires updating the `react-native`, `react`, and `expo` package versions, and setting the correct `sdkVersion` in `app.json`. See the [versioning guide](https://github.com/react-community/create-react-native-app/blob/master/VERSIONS.md) for up-to-date information about package version compatibility.
37 |
38 | ## Available Scripts
39 |
40 | If Yarn was installed when the project was initialized, then dependencies will have been installed via Yarn, and you should probably use it to run these commands as well. Unlike dependency installation, command running syntax is identical for Yarn and NPM at the time of this writing.
41 |
42 | ### `npm start`
43 |
44 | Runs your app in development mode.
45 |
46 | Open it in the [Expo app](https://expo.io) on your phone to view it. It will reload if you save edits to your files, and you will see build errors and logs in the terminal.
47 |
48 | Sometimes you may need to reset or clear the React Native packager's cache. To do so, you can pass the `--reset-cache` flag to the start script:
49 |
50 | ```
51 | npm start -- --reset-cache
52 | # or
53 | yarn start -- --reset-cache
54 | ```
55 |
56 | #### `npm test`
57 |
58 | Runs the [jest](https://github.com/facebook/jest) test runner on your tests.
59 |
60 | #### `npm run ios`
61 |
62 | Like `npm start`, but also attempts to open your app in the iOS Simulator if you're on a Mac and have it installed.
63 |
64 | #### `npm run android`
65 |
66 | Like `npm start`, but also attempts to open your app on a connected Android device or emulator. Requires an installation of Android build tools (see [React Native docs](https://facebook.github.io/react-native/docs/getting-started.html) for detailed setup). We also recommend installing Genymotion as your Android emulator. Once you've finished setting up the native build environment, there are two options for making the right copy of `adb` available to Create React Native App:
67 |
68 | ##### Using Android Studio's `adb`
69 |
70 | 1. Make sure that you can run adb from your terminal.
71 | 2. Open Genymotion and navigate to `Settings -> ADB`. Select “Use custom Android SDK tools” and update with your [Android SDK directory](https://stackoverflow.com/questions/25176594/android-sdk-location).
72 |
73 | ##### Using Genymotion's `adb`
74 |
75 | 1. Find Genymotion’s copy of adb. On macOS for example, this is normally `/Applications/Genymotion.app/Contents/MacOS/tools/`.
76 | 2. Add the Genymotion tools directory to your path (instructions for [Mac](http://osxdaily.com/2014/08/14/add-new-path-to-path-command-line/), [Linux](http://www.computerhope.com/issues/ch001647.htm), and [Windows](https://www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/)).
77 | 3. Make sure that you can run adb from your terminal.
78 |
79 | #### `npm run eject`
80 |
81 | This will start the process of "ejecting" from Create React Native App's build scripts. You'll be asked a couple of questions about how you'd like to build your project.
82 |
83 | **Warning:** Running eject is a permanent action (aside from whatever version control system you use). An ejected app will require you to have an [Xcode and/or Android Studio environment](https://facebook.github.io/react-native/docs/getting-started.html) set up.
84 |
85 | ## Customizing App Display Name and Icon
86 |
87 | You can edit `app.json` to include [configuration keys](https://docs.expo.io/versions/latest/guides/configuration.html) under the `expo` key.
88 |
89 | To change your app's display name, set the `expo.name` key in `app.json` to an appropriate string.
90 |
91 | To set an app icon, set the `expo.icon` key in `app.json` to be either a local path or a URL. It's recommended that you use a 512x512 png file with transparency.
92 |
93 | ## Writing and Running Tests
94 |
95 | This project is set up to use [jest](https://facebook.github.io/jest/) for tests. You can configure whatever testing strategy you like, but jest works out of the box. Create test files in directories called `__tests__` or with the `.test` extension to have the files loaded by jest. See the [the template project](https://github.com/react-community/create-react-native-app/blob/master/react-native-scripts/template/App.test.js) for an example test. The [jest documentation](https://facebook.github.io/jest/docs/getting-started.html) is also a wonderful resource, as is the [React Native testing tutorial](https://facebook.github.io/jest/docs/tutorial-react-native.html).
96 |
97 | ## Environment Variables
98 |
99 | You can configure some of Create React Native App's behavior using environment variables.
100 |
101 | ### Configuring Packager IP Address
102 |
103 | When starting your project, you'll see something like this for your project URL:
104 |
105 | ```
106 | exp://192.168.0.2:19000
107 | ```
108 |
109 | The "manifest" at that URL tells the Expo app how to retrieve and load your app's JavaScript bundle, so even if you load it in the app via a URL like `exp://localhost:19000`, the Expo client app will still try to retrieve your app at the IP address that the start script provides.
110 |
111 | In some cases, this is less than ideal. This might be the case if you need to run your project inside of a virtual machine and you have to access the packager via a different IP address than the one which prints by default. In order to override the IP address or hostname that is detected by Create React Native App, you can specify your own hostname via the `REACT_NATIVE_PACKAGER_HOSTNAME` environment variable:
112 |
113 | Mac and Linux:
114 |
115 | ```
116 | REACT_NATIVE_PACKAGER_HOSTNAME='my-custom-ip-address-or-hostname' npm start
117 | ```
118 |
119 | Windows:
120 | ```
121 | set REACT_NATIVE_PACKAGER_HOSTNAME='my-custom-ip-address-or-hostname'
122 | npm start
123 | ```
124 |
125 | The above example would cause the development server to listen on `exp://my-custom-ip-address-or-hostname:19000`.
126 |
127 | ## Adding Flow
128 |
129 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept.
130 |
131 | React Native works with [Flow](http://flowtype.org/) out of the box, as long as your Flow version matches the one used in the version of React Native.
132 |
133 | To add a local dependency to the correct Flow version to a Create React Native App project, follow these steps:
134 |
135 | 1. Find the Flow `[version]` at the bottom of the included [.flowconfig](.flowconfig)
136 | 2. Run `npm install --save-dev flow-bin@x.y.z` (or `yarn add --dev flow-bin@x.y.z`), where `x.y.z` is the .flowconfig version number.
137 | 3. Add `"flow": "flow"` to the `scripts` section of your `package.json`.
138 | 4. Add `// @flow` to any files you want to type check (for example, to `App.js`).
139 |
140 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors.
141 | You can optionally use a [plugin for your IDE or editor](https://flow.org/en/docs/editors/) for a better integrated experience.
142 |
143 | To learn more about Flow, check out [its documentation](https://flow.org/).
144 |
145 | ## Sharing and Deployment
146 |
147 | Create React Native App does a lot of work to make app setup and development simple and straightforward, but it's very difficult to do the same for deploying to Apple's App Store or Google's Play Store without relying on a hosted service.
148 |
149 | ### Publishing to Expo's React Native Community
150 |
151 | Expo provides free hosting for the JS-only apps created by CRNA, allowing you to share your app through the Expo client app. This requires registration for an Expo account.
152 |
153 | Install the `exp` command-line tool, and run the publish command:
154 |
155 | ```
156 | $ npm i -g exp
157 | $ exp publish
158 | ```
159 |
160 | ### Building an Expo "standalone" app
161 |
162 | You can also use a service like [Expo's standalone builds](https://docs.expo.io/versions/latest/guides/building-standalone-apps.html) if you want to get an IPA/APK for distribution without having to build the native code yourself.
163 |
164 | ### Ejecting from Create React Native App
165 |
166 | If you want to build and deploy your app yourself, you'll need to eject from CRNA and use Xcode and Android Studio.
167 |
168 | This is usually as simple as running `npm run eject` in your project, which will walk you through the process. Make sure to install `react-native-cli` and follow the [native code getting started guide for React Native](https://facebook.github.io/react-native/docs/getting-started.html).
169 |
170 | #### Should I Use ExpoKit?
171 |
172 | If you have made use of Expo APIs while working on your project, then those API calls will stop working if you eject to a regular React Native project. If you want to continue using those APIs, you can eject to "React Native + ExpoKit" which will still allow you to build your own native code and continue using the Expo APIs. See the [ejecting guide](https://github.com/react-community/create-react-native-app/blob/master/EJECTING.md) for more details about this option.
173 |
174 | ## Troubleshooting
175 |
176 | ### Networking
177 |
178 | If you're unable to load your app on your phone due to a network timeout or a refused connection, a good first step is to verify that your phone and computer are on the same network and that they can reach each other. Create React Native App needs access to ports 19000 and 19001 so ensure that your network and firewall settings allow access from your device to your computer on both of these ports.
179 |
180 | Try opening a web browser on your phone and opening the URL that the packager script prints, replacing `exp://` with `http://`. So, for example, if underneath the QR code in your terminal you see:
181 |
182 | ```
183 | exp://192.168.0.1:19000
184 | ```
185 |
186 | Try opening Safari or Chrome on your phone and loading
187 |
188 | ```
189 | http://192.168.0.1:19000
190 | ```
191 |
192 | and
193 |
194 | ```
195 | http://192.168.0.1:19001
196 | ```
197 |
198 | If this works, but you're still unable to load your app by scanning the QR code, please open an issue on the [Create React Native App repository](https://github.com/react-community/create-react-native-app) with details about these steps and any other error messages you may have received.
199 |
200 | If you're not able to load the `http` URL in your phone's web browser, try using the tethering/mobile hotspot feature on your phone (beware of data usage, though), connecting your computer to that WiFi network, and restarting the packager.
201 |
202 | ### iOS Simulator won't open
203 |
204 | If you're on a Mac, there are a few errors that users sometimes see when attempting to `npm run ios`:
205 |
206 | * "non-zero exit code: 107"
207 | * "You may need to install Xcode" but it is already installed
208 | * and others
209 |
210 | There are a few steps you may want to take to troubleshoot these kinds of errors:
211 |
212 | 1. Make sure Xcode is installed and open it to accept the license agreement if it prompts you. You can install it from the Mac App Store.
213 | 2. Open Xcode's Preferences, the Locations tab, and make sure that the `Command Line Tools` menu option is set to something. Sometimes when the CLI tools are first installed by Homebrew this option is left blank, which can prevent Apple utilities from finding the simulator. Make sure to re-run `npm/yarn run ios` after doing so.
214 | 3. If that doesn't work, open the Simulator, and under the app menu select `Reset Contents and Settings...`. After that has finished, quit the Simulator, and re-run `npm/yarn run ios`.
215 |
216 | ### QR Code does not scan
217 |
218 | If you're not able to scan the QR code, make sure your phone's camera is focusing correctly, and also make sure that the contrast on the two colors in your terminal is high enough. For example, WebStorm's default themes may [not have enough contrast](https://github.com/react-community/create-react-native-app/issues/49) for terminal QR codes to be scannable with the system barcode scanners that the Expo app uses.
219 |
220 | If this causes problems for you, you may want to try changing your terminal's color theme to have more contrast, or running Create React Native App from a different terminal. You can also manually enter the URL printed by the packager script in the Expo app's search bar to load it manually.
221 |
--------------------------------------------------------------------------------
/examples/basic/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "expo": {
3 | "sdkVersion": "20.0.0"
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/examples/basic/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "basic",
3 | "version": "0.1.0",
4 | "private": true,
5 | "devDependencies": {
6 | "react-native-scripts": "1.3.0",
7 | "jest-expo": "~20.0.0",
8 | "react-test-renderer": "16.0.0-alpha.12"
9 | },
10 | "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
11 | "scripts": {
12 | "start": "react-native-scripts start",
13 | "eject": "react-native-scripts eject",
14 | "android": "react-native-scripts android",
15 | "ios": "react-native-scripts ios",
16 | "test": "node node_modules/jest/bin/jest.js --watch"
17 | },
18 | "jest": {
19 | "preset": "jest-expo"
20 | },
21 | "dependencies": {
22 | "expo": "^20.0.0",
23 | "react": "16.0.0-alpha.12",
24 | "react-native": "^0.47.0",
25 | "react-native-menu": "*"
26 | }
27 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-menu-packages",
3 | "private": true,
4 | "version": "1.0.0",
5 | "description": "A flexible dropdown menu component for Android and iOS that is similar to Android's Spinner.",
6 | "repository": "https://github.com/jaysoo/react-native-menu",
7 | "author": "Jack Hsu (http://jaysoo.ca/)",
8 | "license": "ISC"
9 | }
10 |
--------------------------------------------------------------------------------
/packages/react-native-menu/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2015, Jack Hsu
2 |
3 | Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
4 |
5 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
6 |
--------------------------------------------------------------------------------
/packages/react-native-menu/README.md:
--------------------------------------------------------------------------------
1 | # react-native-menu
2 |
3 | Please see [https://github.com/jaysoo/react-native-menu](https://github.com/jaysoo/react-native-menu)
--------------------------------------------------------------------------------
/packages/react-native-menu/android.demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaysoo/react-native-menu/7b504475d4e0f59f1f1bc6a0e0ea9fc3cab9a287/packages/react-native-menu/android.demo.gif
--------------------------------------------------------------------------------
/packages/react-native-menu/ios.demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaysoo/react-native-menu/7b504475d4e0f59f1f1bc6a0e0ea9fc3cab9a287/packages/react-native-menu/ios.demo.gif
--------------------------------------------------------------------------------
/packages/react-native-menu/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-menu",
3 | "version": "0.23.0",
4 | "description": "A flexible dropdown menu component for Android and iOS that is similar to Android's Spinner.",
5 | "repository": "https://github.com/jaysoo/react-native-menu",
6 | "scripts": {
7 | "install:example": "cd Example && npm install",
8 | "build:android": "cd Example/android && ./gradlew assembleRelease",
9 | "start:appium": "appium",
10 | "test:setup": "npm run install:example && npm run build:android",
11 | "test:unit": "jest",
12 | "test:feature": "concurrently 'npm run start:appium' 'npm run test:feature:suite'",
13 | "test:feature:suite": "mocha --require babel-core/register test/integration",
14 | "test": "npm run test:setup && npm run test:unit && npm run test:integration"
15 | },
16 | "main": "src/index.js",
17 | "files": [
18 | "android.demo.gif",
19 | "ios.demo.gif",
20 | "README.md",
21 | "LICENSE",
22 | "src"
23 | ],
24 | "keywords": [
25 | "react-native",
26 | "react",
27 | "menu",
28 | "spinner",
29 | "dropdown",
30 | "react-component",
31 | "ios",
32 | "android"
33 | ],
34 | "author": "Jack Hsu (http://jaysoo.ca/)",
35 | "license": "ISC",
36 | "devDependencies": {
37 | "appium": "^1.4.16",
38 | "babel-core": "^6.4.0",
39 | "babel-jest": "*",
40 | "babel-preset-env": "^1.6.0",
41 | "babel-preset-es2015": "^6.3.13",
42 | "babel-preset-react": "^6.3.13",
43 | "babel-preset-react-native": "^3.0.1",
44 | "babel-preset-stage-2": "^6.3.13",
45 | "chai": "^3.4.1",
46 | "chai-as-promised": "^5.2.0",
47 | "colors": "^1.1.2",
48 | "concurrently": "^2.0.0",
49 | "jest": "^20.0.4",
50 | "mocha": "^2.3.4",
51 | "react": "16.0.0-alpha.13",
52 | "react-dom": "16.0.0-alpha.13",
53 | "react-native": "^0.47.2",
54 | "react-test-renderer": "16.0.0-alpha.13",
55 | "sinon": "^1.17.2",
56 | "wd": "^0.4.0"
57 | },
58 | "dependencies": {
59 | "create-react-class": "^15.6.0",
60 | "prop-types": "^15.5.10",
61 | "react-timer-mixin": "^0.13.3"
62 | },
63 | "jest": {
64 | "preset": "react-native",
65 | "modulePathIgnorePatterns": [
66 | "/Example/",
67 | "/examples/"
68 | ],
69 | "testMatch": [
70 | "/src/**/?(*.)test.js"
71 | ],
72 | "verbose": true
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/index.js:
--------------------------------------------------------------------------------
1 | const ReactNative = require('react-native');
2 | const React = require('react');
3 |
4 | // Make our components from factory functions.
5 | const {
6 | Menu,
7 | MenuContext,
8 | MenuOptions,
9 | MenuOption,
10 | MenuTrigger
11 | } = require('./menu')(React, ReactNative);
12 |
13 | Menu.MenuContext = MenuContext;
14 | Menu.MenuOption = MenuOption;
15 | Menu.MenuOptions = MenuOptions;
16 | Menu.MenuTrigger = MenuTrigger;
17 |
18 | module.exports = Menu;
19 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/MenuContext.test.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const React = require('react');
4 | const ReactNative = require('react-native');
5 | const renderer = require('react-test-renderer');
6 | const makeMenuContext = require('../../src/menu/makeMenuContext');
7 |
8 | describe('MenuContext', () => {
9 | let MenuContext;
10 |
11 | beforeEach(() => {
12 | const moduleConfig = {
13 | model: require('./makeModel')(React),
14 | styles: require('./makeStyles')(ReactNative)
15 | };
16 |
17 | MenuContext = makeMenuContext(React, require('react-native'), moduleConfig);
18 | });
19 |
20 | it('renders', () => {
21 | const component = renderer.create()
22 | const tree = component.toJSON()
23 | expect(tree).toMatchSnapshot()
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/__snapshots__/MenuContext.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`MenuContext renders 1`] = `
4 |
12 |
15 |
43 |
44 | `;
45 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/index.js:
--------------------------------------------------------------------------------
1 | const menuModuleFactory = (React, ReactNative) => {
2 | const model = require('./makeModel')(React);
3 | const styles = require('./makeStyles')(ReactNative);
4 |
5 | const config = { model, styles };
6 |
7 | return {
8 | Menu: require('./makeMenu')(React, ReactNative, config),
9 | MenuContext: require('./makeMenuContext')(React, ReactNative, config),
10 | MenuOptions: require('./makeMenuOptions')(React, ReactNative, config),
11 | MenuOption: require('./makeMenuOption')(React, ReactNative, config),
12 | MenuTrigger: require('./makeMenuTrigger')(React, ReactNative, config)
13 | };
14 | };
15 |
16 | module.exports = menuModuleFactory;
17 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/makeAnimatedOptionsContainer.js:
--------------------------------------------------------------------------------
1 | const createClass = require('create-react-class');
2 |
3 | module.exports = (React, ReactNative) => {
4 | const { Animated, Platform } = ReactNative;
5 | const TimerMixin = require('react-timer-mixin');
6 |
7 | // A component that scales in when mounted.
8 | return createClass({
9 | mixins: [TimerMixin],
10 | getInitialState() {
11 | return { scaleAnim: new Animated.Value(Platform.OS === "android" ? 0.01 : 0.001) };
12 | },
13 | componentDidMount() {
14 | this.setTimeout(() => {
15 | Animated.timing(this.state.scaleAnim, {
16 | duration: 60,
17 | toValue: 1
18 | }).start();
19 | }, 16);
20 | },
21 | render() {
22 | return (
23 |
24 | { this.props.children }
25 |
26 | );
27 | }
28 | });
29 | };
30 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/makeMenu.js:
--------------------------------------------------------------------------------
1 | const PropTypes = require('prop-types');
2 | const createClass = require('create-react-class');
3 |
4 | module.exports = (React, ReactNative, { constants, model, styles }) => {
5 | const {
6 | NativeModules: { UIManager },
7 | View
8 | } = ReactNative;
9 |
10 | return createClass({
11 | displayName: 'Menu',
12 | propTypes: {
13 | name: PropTypes.string,
14 | onSelect: PropTypes.func,
15 | onOpen: PropTypes.func,
16 | onClose: PropTypes.func
17 | },
18 | getDefaultProps() {
19 | return {
20 | onSelect: () => {},
21 | onOpen: () => {},
22 | onClose: () => {}
23 | };
24 | },
25 | contextTypes: {
26 | menuController: model.IMenuController
27 | },
28 | childContextTypes: {
29 | getClosestMenuName: PropTypes.func
30 | },
31 | getChildContext() {
32 | return { getClosestMenuName: () => this._name };
33 | },
34 | componentWillMount() {
35 | this._name = this.props.name || this.context.menuController.makeName();
36 | },
37 | componentWillUnmount() {
38 | this.context.menuController.unregisterMenu(this._name);
39 | },
40 | getName() {
41 | return this._name;
42 | },
43 | _register(ref) {
44 | this.context.menuController.registerMenu(this._name, {
45 | ref,
46 | didOpen: () => this.didOpen(),
47 | didClose: () => this.didClose()
48 | });
49 | },
50 | onSelect(value) {
51 | // Call `onSelect` and close the menu, unless the callback returns `false`.
52 | const shouldClose = this.props.onSelect(value) !== false;
53 | if (shouldClose) {
54 | this.context.menuController.close();
55 | }
56 | },
57 | didOpen() {
58 | this.props.onOpen();
59 | },
60 | didClose() {
61 | this.props.onClose();
62 | },
63 | render() {
64 | const { children } = this.props;
65 |
66 | if (React.Children.count(children) < 2) {
67 | throw new Error('Menu component is missing required children components MenuTrigger and MenuOptions.')
68 | }
69 |
70 | const { rest, options } = children.reduce((accum, child) => {
71 | switch (child.type.displayName) {
72 | case 'MenuOptions':
73 | if (accum.options) {
74 | throw new Error('Menu component has two MenuOptions children, but it can only use one. Please remove one of them.')
75 | }
76 | accum.options = React.cloneElement(child, {onSelect: this.onSelect});
77 | break;
78 | default:
79 | accum.rest.push(child);
80 | }
81 | return accum;
82 | }, {options: null, rest: []});
83 |
84 | if (!options) {
85 | throw new Error('Menu component is missing required child component MenuOptions.')
86 | }
87 |
88 | this.context.menuController.registerOptionsElement(this._name, options);
89 |
90 | // view can't collapse see https://github.com/facebook/react-native/issues/3282
91 | return (
92 |
93 | { rest }
94 |
95 | );
96 | }
97 | });
98 | };
99 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/makeMenuContext.js:
--------------------------------------------------------------------------------
1 | const TimerMixin = require('react-timer-mixin');
2 | const PropTypes = require('prop-types');
3 | const createClass = require('create-react-class');
4 |
5 | let nextID = 1;
6 |
7 | module.exports = (React, ReactNative, { model, styles }) => {
8 | const {
9 | UIManager,
10 | TouchableWithoutFeedback,
11 | ScrollView,
12 | View,
13 | BackHandler
14 | } = ReactNative;
15 | const AnimatedOptionsContainer = require('./makeAnimatedOptionsContainer')(React, ReactNative);
16 |
17 | // Calls a function once, then never again.
18 | const once = (fn) => {
19 | let called = false;
20 | return (...args) => {
21 | if (!called) {
22 | called = true;
23 | fn(...args);
24 | }
25 | };
26 | };
27 |
28 | const defaultOptionsContainerRenderer = (options) => (
29 |
30 | {options}
31 |
32 | );
33 |
34 | const makeOptions = (options, { top, right }) => {
35 | const { optionsContainerStyle, renderOptionsContainer = defaultOptionsContainerRenderer} = options.props;
36 | return (
37 |
38 | { renderOptionsContainer(options) }
39 |
40 | );
41 | };
42 |
43 | const NULL_HOOKS = {
44 | didOpen: () => {},
45 | didClose: () => {}
46 | }
47 |
48 | /*
49 | * The MenuContext provides a tunnel for descendant menu components to access
50 | * top-level methods. It also allows the element to be placed
51 | * properly.
52 | */
53 | return createClass({
54 | displayName: 'MenuContext',
55 | propTypes: {
56 | detectBackHandler: PropTypes.bool,
57 | },
58 | getDefaultProps() {
59 | return {
60 | detectBackHandler: true,
61 | };
62 | },
63 | mixins: [TimerMixin],
64 |
65 | // Public methods
66 | isMenuOpen() {
67 | return this.state.openedMenu
68 | },
69 | openMenu(name) {
70 | const handle = ReactNative.findNodeHandle(this._menus[name].ref);
71 | UIManager.measure(handle, (x, y, w, h, px, py) => {
72 | this._menus[name].measurements = { x, y, w, h, px, py };
73 |
74 | this.setState({
75 | openedMenu: name,
76 | menuOptions: this._makeAndPositionOptions(name, this._menus[name].measurements),
77 | backdropWidth: this._ownMeasurements.w
78 | });
79 |
80 | this._activeMenuHooks = this._menus[name];
81 | this._activeMenuHooks && this._activeMenuHooks.didOpen();
82 | });
83 | },
84 | closeMenu() {
85 | if (this.props.onCloseMenu) {
86 | this.props.onCloseMenu(this.state)
87 | }
88 | this.setState({
89 | openedMenu: '',
90 | menuOptions: null
91 | });
92 |
93 | this._activeMenuHooks && this._activeMenuHooks.didClose();
94 | this._activeMenuHooks = NULL_HOOKS;
95 | },
96 | toggleMenu(name) {
97 | if (this.state.openedMenu === name) {
98 | this.closeMenu(name);
99 | } else {
100 | this.openMenu(name);
101 | }
102 | },
103 |
104 | // Private and lifecycle methods
105 | getInitialState() {
106 | return {
107 | openedMenu: '',
108 | menuOptions: null,
109 | optionsTop: 0,
110 | optionsRight: 0,
111 | backdropWidth: 0
112 | };
113 | },
114 | childContextTypes: {
115 | menuController: model.IMenuController
116 | },
117 | getChildContext() {
118 | const menuController = {
119 | open: this.openMenu,
120 | close: this.closeMenu,
121 | toggle: this.toggleMenu,
122 | registerMenu: this._registerMenu,
123 | unregisterMenu: this._unregisterMenu,
124 | registerOptionsElement: this._registerOptionsElement,
125 | makeName: this._makeName
126 | };
127 | return { menuController };
128 | },
129 | componentWillMount() {
130 | this._menus = {};
131 | this._options = {};
132 | // Only do this once on initial layout.
133 | this.onLayout = once(this.onLayout);
134 | },
135 | handleBackHandler() {
136 | if (this.isMenuOpen()){
137 | this.closeMenu();
138 | return true;
139 | }
140 | return false;
141 | },
142 | onLayout() {
143 | const handle = ReactNative.findNodeHandle(this.refs.Container);
144 | UIManager.measure(handle, (x, y, w, h, px, py) => {
145 | this._ownMeasurements = {x, y, w, h, px, py};
146 | });
147 | },
148 | _registerMenu(name, hooks) {
149 | if (this._menus[name]) {
150 | console.warn(`Menu ${name} has already been registered in this context. Please provide a different name.`);
151 | }
152 |
153 | if (this.props.detectBackHandler){
154 | BackHandler.removeEventListener('hardwareBackPress', this.handleBackHandler); //Override previous listener
155 | BackHandler.addEventListener('hardwareBackPress', this.handleBackHandler);
156 | }
157 | this._menus[name] = hooks;
158 | },
159 | _unregisterMenu(name) {
160 | delete this._menus[name];
161 | delete this._options[name];
162 | },
163 | _registerOptionsElement(name, options) {
164 | // If options are already set and visible, skip the update.
165 | if (this.state.menuOptions === options) {
166 | return;
167 | }
168 | this._options[name] = options;
169 | // If the menu is already open, re-render the options.
170 | this.setTimeout(() => {
171 | if (this.state.openedMenu === name) {
172 | this.setState({ menuOptions: this._makeAndPositionOptions(name, this._menus[name].measurements) });
173 | }
174 | }, 16);
175 | },
176 | _makeName() {
177 | return `menu-${nextID++}`;
178 | },
179 | _makeAndPositionOptions(name, menuMeasurements) {
180 | const options = this._options[name];
181 | const { w: menuWidth, px: menuPX, py: menuPY } = menuMeasurements;
182 | const { w: ownWidth, px: ownPX, py: ownPY } = this._ownMeasurements;
183 | const optionsTop = menuPY - ownPY;
184 | const optionsRight = ownWidth + ownPX - menuPX - menuWidth;
185 | return makeOptions(options, { top: optionsTop, right: optionsRight });
186 | },
187 |
188 | render() {
189 | return (
190 |
191 |
192 | { this.props.children }
193 |
194 |
195 |
197 |
198 | { this.state.menuOptions }
199 |
200 | )
201 | }
202 | });
203 | };
204 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/makeMenuOption.js:
--------------------------------------------------------------------------------
1 | const createClass = require('create-react-class');
2 |
3 | module.exports = (React, ReactNative, { model, styles }) => {
4 | const { View, TouchableWithoutFeedback } = ReactNative;
5 |
6 | return createClass({
7 | displayName: 'MenuOption',
8 | contextTypes: {
9 | menuController: model.IMenuController
10 | },
11 | onPress() {
12 | !this.props.disabled && this.props.onPress(this.props.value)
13 | },
14 | render() {
15 | if(this.props.renderTouchable) {
16 | return React.cloneElement(this.props.renderTouchable(), {onPress: this.onPress}, (
17 |
18 | { this.props.children }
19 |
20 | ));
21 | }
22 | return (
23 |
24 |
25 | { this.props.children }
26 |
27 |
28 | );
29 | }
30 | });
31 | };
32 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/makeMenuOptions.js:
--------------------------------------------------------------------------------
1 | const createClass = require('create-react-class');
2 |
3 | module.exports = (React, ReactNative, { styles }) => {
4 | const { TouchableWithoutFeedback, View } = ReactNative;
5 |
6 | return createClass({
7 | displayName: 'MenuOptions',
8 | onSelect(value) {
9 | this.props.onSelect(value);
10 | },
11 | render() {
12 | return (
13 |
14 |
15 | { React.Children.map(this.props.children, (x) => (
16 | React.cloneElement(x, {onPress: this.onSelect})
17 | )) }
18 |
19 |
20 | );
21 | }
22 | });
23 | };
24 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/makeMenuTrigger.js:
--------------------------------------------------------------------------------
1 | const PropTypes = require('prop-types');
2 | const createClass = require('create-react-class');
3 |
4 | module.exports = (React, ReactNative, { model }) => {
5 | const { TouchableWithoutFeedback, View } = ReactNative;
6 |
7 | return createClass({
8 | displayName: 'MenuTrigger',
9 | propTypes: {
10 | disabled: PropTypes.bool,
11 | renderTouchable: PropTypes.func
12 | },
13 | getDefaultProps() {
14 | return {disabled: false}
15 | },
16 | contextTypes: {
17 | menuController: model.IMenuController,
18 | getClosestMenuName: PropTypes.func.isRequired
19 | },
20 | onPress() {
21 | if (!this.props.disabled) {
22 | const { menuController, getClosestMenuName } = this.context;
23 | menuController.toggle(getClosestMenuName());
24 | }
25 | },
26 | render() {
27 | if(this.props.renderTouchable) {
28 | return React.cloneElement(this.props.renderTouchable(), {onPress: this.onPress}, (
29 |
30 | { this.props.children }
31 |
32 | ));
33 | }
34 | return (
35 |
36 |
37 | { this.props.children }
38 |
39 |
40 | );
41 | }
42 | });
43 | };
44 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/makeModel.js:
--------------------------------------------------------------------------------
1 | const PropTypes = require('prop-types');
2 |
3 | module.exports = (React) => {
4 | const { shape, func } = PropTypes;
5 |
6 | const IMenuController = shape({
7 | open: func.isRequired,
8 | close: func.isRequired,
9 | toggle: func.isRequired,
10 | registerOptionsElement: func.isRequired
11 | });
12 |
13 | return { IMenuController };
14 | };
15 |
16 |
--------------------------------------------------------------------------------
/packages/react-native-menu/src/menu/makeStyles.js:
--------------------------------------------------------------------------------
1 | module.exports = (ReactNative) => {
2 | const { Dimensions, StyleSheet } = ReactNative;
3 | const window = Dimensions.get('window');
4 |
5 | return StyleSheet.create({
6 | optionsContainer: {
7 | position: 'absolute',
8 | borderRadius: 2,
9 | backgroundColor: 'white',
10 | width: 200,
11 |
12 | // Shadow only works on iOS.
13 | shadowColor: 'black',
14 | shadowOpacity: 0.3,
15 | shadowOffset: { width: 3, height: 3 },
16 | shadowRadius: 4,
17 |
18 | // This will elevate the view on Android, causing shadow to be drawn.
19 | elevation: 8
20 | },
21 | options: {
22 | flex: 1
23 | },
24 | optionsHidden: {
25 | top: window.height,
26 | bottom: -window.height
27 | },
28 | option: {
29 | padding: 10,
30 | backgroundColor: 'transparent',
31 | flex: 1
32 | },
33 | backdrop: {
34 | opacity: 0,
35 | position: 'absolute',
36 | top: window.height,
37 | bottom: -window.height,
38 | left: 0
39 | }
40 | });
41 | };
42 |
--------------------------------------------------------------------------------
/packages/react-native-menu/test/integration/menu-tests.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const { should } = require('../support/setup');
4 |
5 | const wd = require('wd');
6 | const serverConfigs = require('../support/appium-servers');
7 |
8 | describe('Menu tests', function () {
9 | this.timeout(200000);
10 | let driver;
11 |
12 | beforeEach(function () {
13 | const serverConfig = serverConfigs.local;
14 | driver = wd.promiseChainRemote(serverConfig);
15 |
16 | const desired = {
17 | ...require('../support/caps').android19,
18 | app: require('../support/apps').androidDemo
19 | };
20 |
21 | return driver
22 | .init(desired)
23 | .setImplicitWaitTimeout(2000);
24 | });
25 |
26 | afterEach(function () {
27 | return driver.quit();
28 | });
29 |
30 | it('renders menu', () => {
31 | return driver
32 | .elementByXPath('//android.widget.TextView[@text=\'OPEN FIRST MENU\']')
33 | .click()
34 | .elementByXPath('//android.widget.TextView[@text=\'Normal option\']')
35 | .should.eventually.exist;
36 | });
37 |
38 | it('invokes callback when option is selected', () => {
39 | return driver
40 | .elementByXPath('//android.widget.TextView[@text=\'OPEN FIRST MENU\']')
41 | .click()
42 | .elementByXPath('//android.widget.TextView[@text=\'Normal option\']')
43 | .click()
44 | .elementByXPath('//android.widget.TextView[@text=\'You selected "normal"\']')
45 | .should.eventually.exist;
46 | });
47 |
48 | it('does not open menu for disabled triggers', () => {
49 | return driver
50 | .elementByXPath('//android.widget.TextView[@text=\'OPEN SECOND MENU\']')
51 | .click()
52 | .elementByXPath('//android.widget.TextView[@text=\'disable first menu\']')
53 | .click()
54 | .elementByXPath('//android.widget.TextView[@text=\'OPEN FIRST MENU\']')
55 | .click()
56 | .elementsByAndroidUIAutomator('new UiSelector().text("You selected \"normal\"")')
57 | .should.eventually.be.empty;
58 | });
59 | });
60 |
--------------------------------------------------------------------------------
/packages/react-native-menu/test/support/appium-servers.js:
--------------------------------------------------------------------------------
1 | exports.local = {
2 | host: 'localhost',
3 | port: 4723
4 | };
5 |
6 | //exports.sauce = {
7 | // host: 'ondemand.saucelabs.com',
8 | // port: 80,
9 | // username: process.env.SAUCE_USERNAME,
10 | // password: process.env.SAUCE_ACCESS_KEY
11 | //};
12 |
--------------------------------------------------------------------------------
/packages/react-native-menu/test/support/apps.js:
--------------------------------------------------------------------------------
1 | //exports.iosWebviewApp = "sample-code/apps/WebViewApp/build/release-iphonesimulator/WebViewApp.app";
2 | exports.androidDemo = '../../Example/android/app/build/outputs/apk/app-release-unsigned.apk';
3 |
--------------------------------------------------------------------------------
/packages/react-native-menu/test/support/caps.js:
--------------------------------------------------------------------------------
1 | exports.ios81 = {
2 | browserName: '',
3 | 'appium-version': '1.3',
4 | platformName: 'iOS',
5 | platformVersion: '8.1',
6 | deviceName: 'iPhone Simulator',
7 | waitForAppScript: true,
8 | app: undefined // will be set later
9 | };
10 |
11 | exports.android18 = {
12 | browserName: '',
13 | 'appium-version': '1.4.16',
14 | platformName: 'Android',
15 | platformVersion: '4.3',
16 | deviceName: 'Android Emulator',
17 | waitForAppScript: true,
18 | app: null // will be set later
19 | };
20 |
21 | exports.android19 = {
22 | browserName: '',
23 | 'appium-version': '1.4.16',
24 | platformName: 'Android',
25 | platformVersion: '4.4.2',
26 | deviceName: 'Android Emulator',
27 | waitForAppScript: true,
28 | app: null // will be set later
29 | };
--------------------------------------------------------------------------------
/packages/react-native-menu/test/support/setup.js:
--------------------------------------------------------------------------------
1 | const wd = require('wd');
2 |
3 | require('colors');
4 | const chai = require('chai');
5 | const chaiAsPromised = require('chai-as-promised');
6 | chai.use(chaiAsPromised);
7 | const should = chai.should();
8 | chaiAsPromised.transferPromiseness = wd.transferPromiseness;
9 |
10 | exports.should = should;
11 |
--------------------------------------------------------------------------------
/yarn.lock:
--------------------------------------------------------------------------------
1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
2 | # yarn lockfile v1
3 |
4 |
5 |
--------------------------------------------------------------------------------