TextInput.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @flow
  8. * @format
  9. */
  10. 'use strict';
  11. const DeprecatedTextInputPropTypes = require('../../DeprecatedPropTypes/DeprecatedTextInputPropTypes');
  12. const Platform = require('../../Utilities/Platform');
  13. const React = require('react');
  14. const ReactNative = require('../../Renderer/shims/ReactNative');
  15. const StyleSheet = require('../../StyleSheet/StyleSheet');
  16. const Text = require('../../Text/Text');
  17. const TextAncestor = require('../../Text/TextAncestor');
  18. const TextInputState = require('./TextInputState');
  19. const TouchableWithoutFeedback = require('../Touchable/TouchableWithoutFeedback');
  20. const invariant = require('invariant');
  21. const nullthrows = require('nullthrows');
  22. const setAndForwardRef = require('../../Utilities/setAndForwardRef');
  23. import type {TextStyleProp, ViewStyleProp} from '../../StyleSheet/StyleSheet';
  24. import type {ColorValue} from '../../StyleSheet/StyleSheetTypes';
  25. import type {ViewProps} from '../View/ViewPropTypes';
  26. import type {SyntheticEvent, ScrollEvent} from '../../Types/CoreEventTypes';
  27. import type {PressEvent} from '../../Types/CoreEventTypes';
  28. import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
  29. import type {TextInputNativeCommands} from './TextInputNativeCommands';
  30. const {useEffect, useRef, useState} = React;
  31. type ReactRefSetter<T> = {current: null | T, ...} | ((ref: null | T) => mixed);
  32. let AndroidTextInput;
  33. let AndroidTextInputCommands;
  34. let RCTSinglelineTextInputView;
  35. let RCTSinglelineTextInputNativeCommands;
  36. let RCTMultilineTextInputView;
  37. let RCTMultilineTextInputNativeCommands;
  38. if (Platform.OS === 'android') {
  39. AndroidTextInput = require('./AndroidTextInputNativeComponent').default;
  40. AndroidTextInputCommands = require('./AndroidTextInputNativeComponent')
  41. .Commands;
  42. } else if (Platform.OS === 'ios') {
  43. RCTSinglelineTextInputView = require('./RCTSingelineTextInputNativeComponent')
  44. .default;
  45. RCTSinglelineTextInputNativeCommands = require('./RCTSingelineTextInputNativeComponent')
  46. .Commands;
  47. RCTMultilineTextInputView = require('./RCTMultilineTextInputNativeComponent')
  48. .default;
  49. RCTMultilineTextInputNativeCommands = require('./RCTMultilineTextInputNativeComponent')
  50. .Commands;
  51. }
  52. export type ChangeEvent = SyntheticEvent<
  53. $ReadOnly<{|
  54. eventCount: number,
  55. target: number,
  56. text: string,
  57. |}>,
  58. >;
  59. export type TextInputEvent = SyntheticEvent<
  60. $ReadOnly<{|
  61. eventCount: number,
  62. previousText: string,
  63. range: $ReadOnly<{|
  64. start: number,
  65. end: number,
  66. |}>,
  67. target: number,
  68. text: string,
  69. |}>,
  70. >;
  71. export type ContentSizeChangeEvent = SyntheticEvent<
  72. $ReadOnly<{|
  73. target: number,
  74. contentSize: $ReadOnly<{|
  75. width: number,
  76. height: number,
  77. |}>,
  78. |}>,
  79. >;
  80. type TargetEvent = SyntheticEvent<
  81. $ReadOnly<{|
  82. target: number,
  83. |}>,
  84. >;
  85. export type BlurEvent = TargetEvent;
  86. export type FocusEvent = TargetEvent;
  87. type Selection = $ReadOnly<{|
  88. start: number,
  89. end: number,
  90. |}>;
  91. export type SelectionChangeEvent = SyntheticEvent<
  92. $ReadOnly<{|
  93. selection: Selection,
  94. target: number,
  95. |}>,
  96. >;
  97. export type KeyPressEvent = SyntheticEvent<
  98. $ReadOnly<{|
  99. key: string,
  100. target?: ?number,
  101. eventCount?: ?number,
  102. |}>,
  103. >;
  104. export type EditingEvent = SyntheticEvent<
  105. $ReadOnly<{|
  106. eventCount: number,
  107. text: string,
  108. target: number,
  109. |}>,
  110. >;
  111. type DataDetectorTypesType =
  112. | 'phoneNumber'
  113. | 'link'
  114. | 'address'
  115. | 'calendarEvent'
  116. | 'none'
  117. | 'all';
  118. export type KeyboardType =
  119. // Cross Platform
  120. | 'default'
  121. | 'email-address'
  122. | 'numeric'
  123. | 'phone-pad'
  124. | 'number-pad'
  125. | 'decimal-pad'
  126. // iOS-only
  127. | 'ascii-capable'
  128. | 'numbers-and-punctuation'
  129. | 'url'
  130. | 'name-phone-pad'
  131. | 'twitter'
  132. | 'web-search'
  133. // iOS 10+ only
  134. | 'ascii-capable-number-pad'
  135. // Android-only
  136. | 'visible-password';
  137. export type ReturnKeyType =
  138. // Cross Platform
  139. | 'done'
  140. | 'go'
  141. | 'next'
  142. | 'search'
  143. | 'send'
  144. // Android-only
  145. | 'none'
  146. | 'previous'
  147. // iOS-only
  148. | 'default'
  149. | 'emergency-call'
  150. | 'google'
  151. | 'join'
  152. | 'route'
  153. | 'yahoo';
  154. export type AutoCapitalize = 'none' | 'sentences' | 'words' | 'characters';
  155. export type TextContentType =
  156. | 'none'
  157. | 'URL'
  158. | 'addressCity'
  159. | 'addressCityAndState'
  160. | 'addressState'
  161. | 'countryName'
  162. | 'creditCardNumber'
  163. | 'emailAddress'
  164. | 'familyName'
  165. | 'fullStreetAddress'
  166. | 'givenName'
  167. | 'jobTitle'
  168. | 'location'
  169. | 'middleName'
  170. | 'name'
  171. | 'namePrefix'
  172. | 'nameSuffix'
  173. | 'nickname'
  174. | 'organizationName'
  175. | 'postalCode'
  176. | 'streetAddressLine1'
  177. | 'streetAddressLine2'
  178. | 'sublocality'
  179. | 'telephoneNumber'
  180. | 'username'
  181. | 'password'
  182. | 'newPassword'
  183. | 'oneTimeCode';
  184. type PasswordRules = string;
  185. type IOSProps = $ReadOnly<{|
  186. /**
  187. * If `false`, disables spell-check style (i.e. red underlines).
  188. * The default value is inherited from `autoCorrect`.
  189. * @platform ios
  190. */
  191. spellCheck?: ?boolean,
  192. /**
  193. * Determines the color of the keyboard.
  194. * @platform ios
  195. */
  196. keyboardAppearance?: ?('default' | 'light' | 'dark'),
  197. /**
  198. * If `true`, the keyboard disables the return key when there is no text and
  199. * automatically enables it when there is text. The default value is `false`.
  200. * @platform ios
  201. */
  202. enablesReturnKeyAutomatically?: ?boolean,
  203. /**
  204. * When the clear button should appear on the right side of the text view.
  205. * This property is supported only for single-line TextInput component.
  206. * @platform ios
  207. */
  208. clearButtonMode?: ?('never' | 'while-editing' | 'unless-editing' | 'always'),
  209. /**
  210. * If `true`, clears the text field automatically when editing begins.
  211. * @platform ios
  212. */
  213. clearTextOnFocus?: ?boolean,
  214. /**
  215. * Determines the types of data converted to clickable URLs in the text input.
  216. * Only valid if `multiline={true}` and `editable={false}`.
  217. * By default no data types are detected.
  218. *
  219. * You can provide one type or an array of many types.
  220. *
  221. * Possible values for `dataDetectorTypes` are:
  222. *
  223. * - `'phoneNumber'`
  224. * - `'link'`
  225. * - `'address'`
  226. * - `'calendarEvent'`
  227. * - `'none'`
  228. * - `'all'`
  229. *
  230. * @platform ios
  231. */
  232. dataDetectorTypes?:
  233. | ?DataDetectorTypesType
  234. | $ReadOnlyArray<DataDetectorTypesType>,
  235. /**
  236. * An optional identifier which links a custom InputAccessoryView to
  237. * this text input. The InputAccessoryView is rendered above the
  238. * keyboard when this text input is focused.
  239. * @platform ios
  240. */
  241. inputAccessoryViewID?: ?string,
  242. /**
  243. * Give the keyboard and the system information about the
  244. * expected semantic meaning for the content that users enter.
  245. * @platform ios
  246. */
  247. textContentType?: ?TextContentType,
  248. /**
  249. * Provide rules for your password.
  250. * For example, say you want to require a password with at least eight characters consisting of a mix of uppercase and lowercase letters, at least one number, and at most two consecutive characters.
  251. * "required: upper; required: lower; required: digit; max-consecutive: 2; minlength: 8;"
  252. * @platform ios
  253. */
  254. passwordRules?: ?PasswordRules,
  255. /*
  256. * If `true`, allows TextInput to pass touch events to the parent component.
  257. * This allows components to be swipeable from the TextInput on iOS,
  258. * as is the case on Android by default.
  259. * If `false`, TextInput always asks to handle the input (except when disabled).
  260. * @platform ios
  261. */
  262. rejectResponderTermination?: ?boolean,
  263. /**
  264. * If `false`, scrolling of the text view will be disabled.
  265. * The default value is `true`. Does only work with 'multiline={true}'.
  266. * @platform ios
  267. */
  268. scrollEnabled?: ?boolean,
  269. |}>;
  270. type AndroidProps = $ReadOnly<{|
  271. /**
  272. * Determines which content to suggest on auto complete, e.g.`username`.
  273. * To disable auto complete, use `off`.
  274. *
  275. * *Android Only*
  276. *
  277. * The following values work on Android only:
  278. *
  279. * - `username`
  280. * - `password`
  281. * - `email`
  282. * - `name`
  283. * - `tel`
  284. * - `street-address`
  285. * - `postal-code`
  286. * - `cc-number`
  287. * - `cc-csc`
  288. * - `cc-exp`
  289. * - `cc-exp-month`
  290. * - `cc-exp-year`
  291. * - `off`
  292. *
  293. * @platform android
  294. */
  295. autoCompleteType?: ?(
  296. | 'cc-csc'
  297. | 'cc-exp'
  298. | 'cc-exp-month'
  299. | 'cc-exp-year'
  300. | 'cc-number'
  301. | 'email'
  302. | 'name'
  303. | 'password'
  304. | 'postal-code'
  305. | 'street-address'
  306. | 'tel'
  307. | 'username'
  308. | 'off'
  309. ),
  310. /**
  311. * Sets the return key to the label. Use it instead of `returnKeyType`.
  312. * @platform android
  313. */
  314. returnKeyLabel?: ?string,
  315. /**
  316. * Sets the number of lines for a `TextInput`. Use it with multiline set to
  317. * `true` to be able to fill the lines.
  318. * @platform android
  319. */
  320. numberOfLines?: ?number,
  321. /**
  322. * When `false`, if there is a small amount of space available around a text input
  323. * (e.g. landscape orientation on a phone), the OS may choose to have the user edit
  324. * the text inside of a full screen text input mode. When `true`, this feature is
  325. * disabled and users will always edit the text directly inside of the text input.
  326. * Defaults to `false`.
  327. * @platform android
  328. */
  329. disableFullscreenUI?: ?boolean,
  330. /**
  331. * Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced`
  332. * The default value is `simple`.
  333. * @platform android
  334. */
  335. textBreakStrategy?: ?('simple' | 'highQuality' | 'balanced'),
  336. /**
  337. * The color of the `TextInput` underline.
  338. * @platform android
  339. */
  340. underlineColorAndroid?: ?ColorValue,
  341. /**
  342. * If defined, the provided image resource will be rendered on the left.
  343. * The image resource must be inside `/android/app/src/main/res/drawable` and referenced
  344. * like
  345. * ```
  346. * <TextInput
  347. * inlineImageLeft='search_icon'
  348. * />
  349. * ```
  350. * @platform android
  351. */
  352. inlineImageLeft?: ?string,
  353. /**
  354. * Padding between the inline image, if any, and the text input itself.
  355. * @platform android
  356. */
  357. inlineImagePadding?: ?number,
  358. importantForAutofill?: ?(
  359. | 'auto'
  360. | 'no'
  361. | 'noExcludeDescendants'
  362. | 'yes'
  363. | 'yesExcludeDescendants'
  364. ),
  365. /**
  366. * When `false`, it will prevent the soft keyboard from showing when the field is focused.
  367. * Defaults to `true`.
  368. * @platform android
  369. */
  370. showSoftInputOnFocus?: ?boolean,
  371. |}>;
  372. export type Props = $ReadOnly<{|
  373. ...$Diff<ViewProps, $ReadOnly<{|style: ?ViewStyleProp|}>>,
  374. ...IOSProps,
  375. ...AndroidProps,
  376. /**
  377. * Can tell `TextInput` to automatically capitalize certain characters.
  378. *
  379. * - `characters`: all characters.
  380. * - `words`: first letter of each word.
  381. * - `sentences`: first letter of each sentence (*default*).
  382. * - `none`: don't auto capitalize anything.
  383. */
  384. autoCapitalize?: ?AutoCapitalize,
  385. /**
  386. * If `false`, disables auto-correct. The default value is `true`.
  387. */
  388. autoCorrect?: ?boolean,
  389. /**
  390. * If `true`, focuses the input on `componentDidMount`.
  391. * The default value is `false`.
  392. */
  393. autoFocus?: ?boolean,
  394. /**
  395. * Specifies whether fonts should scale to respect Text Size accessibility settings. The
  396. * default is `true`.
  397. */
  398. allowFontScaling?: ?boolean,
  399. /**
  400. * Specifies largest possible scale a font can reach when `allowFontScaling` is enabled.
  401. * Possible values:
  402. * `null/undefined` (default): inherit from the parent node or the global default (0)
  403. * `0`: no max, ignore parent/global default
  404. * `>= 1`: sets the maxFontSizeMultiplier of this node to this value
  405. */
  406. maxFontSizeMultiplier?: ?number,
  407. /**
  408. * If `false`, text is not editable. The default value is `true`.
  409. */
  410. editable?: ?boolean,
  411. /**
  412. * Determines which keyboard to open, e.g.`numeric`.
  413. *
  414. * The following values work across platforms:
  415. *
  416. * - `default`
  417. * - `numeric`
  418. * - `number-pad`
  419. * - `decimal-pad`
  420. * - `email-address`
  421. * - `phone-pad`
  422. *
  423. * *iOS Only*
  424. *
  425. * The following values work on iOS only:
  426. *
  427. * - `ascii-capable`
  428. * - `numbers-and-punctuation`
  429. * - `url`
  430. * - `name-phone-pad`
  431. * - `twitter`
  432. * - `web-search`
  433. *
  434. * *Android Only*
  435. *
  436. * The following values work on Android only:
  437. *
  438. * - `visible-password`
  439. *
  440. * On Android devices manufactured by Xiaomi with Android Q, 'email-address'
  441. * type will be replaced in native by 'default' to prevent a system related crash.
  442. */
  443. keyboardType?: ?KeyboardType,
  444. /**
  445. * Determines how the return key should look. On Android you can also use
  446. * `returnKeyLabel`.
  447. *
  448. * *Cross platform*
  449. *
  450. * The following values work across platforms:
  451. *
  452. * - `done`
  453. * - `go`
  454. * - `next`
  455. * - `search`
  456. * - `send`
  457. *
  458. * *Android Only*
  459. *
  460. * The following values work on Android only:
  461. *
  462. * - `none`
  463. * - `previous`
  464. *
  465. * *iOS Only*
  466. *
  467. * The following values work on iOS only:
  468. *
  469. * - `default`
  470. * - `emergency-call`
  471. * - `google`
  472. * - `join`
  473. * - `route`
  474. * - `yahoo`
  475. */
  476. returnKeyType?: ?ReturnKeyType,
  477. /**
  478. * Limits the maximum number of characters that can be entered. Use this
  479. * instead of implementing the logic in JS to avoid flicker.
  480. */
  481. maxLength?: ?number,
  482. /**
  483. * If `true`, the text input can be multiple lines.
  484. * The default value is `false`.
  485. */
  486. multiline?: ?boolean,
  487. /**
  488. * Callback that is called when the text input is blurred.
  489. */
  490. onBlur?: ?(e: BlurEvent) => mixed,
  491. /**
  492. * Callback that is called when the text input is focused.
  493. */
  494. onFocus?: ?(e: FocusEvent) => mixed,
  495. /**
  496. * Callback that is called when the text input's text changes.
  497. */
  498. onChange?: ?(e: ChangeEvent) => mixed,
  499. /**
  500. * Callback that is called when the text input's text changes.
  501. * Changed text is passed as an argument to the callback handler.
  502. */
  503. onChangeText?: ?(text: string) => mixed,
  504. /**
  505. * Callback that is called when the text input's content size changes.
  506. * This will be called with
  507. * `{ nativeEvent: { contentSize: { width, height } } }`.
  508. *
  509. * Only called for multiline text inputs.
  510. */
  511. onContentSizeChange?: ?(e: ContentSizeChangeEvent) => mixed,
  512. /**
  513. * Callback that is called when text input ends.
  514. */
  515. onEndEditing?: ?(e: EditingEvent) => mixed,
  516. /**
  517. * Callback that is called when the text input selection is changed.
  518. * This will be called with
  519. * `{ nativeEvent: { selection: { start, end } } }`.
  520. */
  521. onSelectionChange?: ?(e: SelectionChangeEvent) => mixed,
  522. /**
  523. * Callback that is called when the text input's submit button is pressed.
  524. * Invalid if `multiline={true}` is specified.
  525. */
  526. onSubmitEditing?: ?(e: EditingEvent) => mixed,
  527. /**
  528. * Callback that is called when a key is pressed.
  529. * This will be called with `{ nativeEvent: { key: keyValue } }`
  530. * where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and
  531. * the typed-in character otherwise including `' '` for space.
  532. * Fires before `onChange` callbacks.
  533. */
  534. onKeyPress?: ?(e: KeyPressEvent) => mixed,
  535. /**
  536. * Invoked on content scroll with `{ nativeEvent: { contentOffset: { x, y } } }`.
  537. * May also contain other properties from ScrollEvent but on Android contentSize
  538. * is not provided for performance reasons.
  539. */
  540. onScroll?: ?(e: ScrollEvent) => mixed,
  541. /**
  542. * The string that will be rendered before text input has been entered.
  543. */
  544. placeholder?: ?Stringish,
  545. /**
  546. * The text color of the placeholder string.
  547. */
  548. placeholderTextColor?: ?ColorValue,
  549. /**
  550. * If `true`, the text input obscures the text entered so that sensitive text
  551. * like passwords stay secure. The default value is `false`. Does not work with 'multiline={true}'.
  552. */
  553. secureTextEntry?: ?boolean,
  554. /**
  555. * The highlight and cursor color of the text input.
  556. */
  557. selectionColor?: ?ColorValue,
  558. /**
  559. * The start and end of the text input's selection. Set start and end to
  560. * the same value to position the cursor.
  561. */
  562. selection?: ?$ReadOnly<{|
  563. start: number,
  564. end?: ?number,
  565. |}>,
  566. /**
  567. * The value to show for the text input. `TextInput` is a controlled
  568. * component, which means the native value will be forced to match this
  569. * value prop if provided. For most uses, this works great, but in some
  570. * cases this may cause flickering - one common cause is preventing edits
  571. * by keeping value the same. In addition to simply setting the same value,
  572. * either set `editable={false}`, or set/update `maxLength` to prevent
  573. * unwanted edits without flicker.
  574. */
  575. value?: ?Stringish,
  576. /**
  577. * Provides an initial value that will change when the user starts typing.
  578. * Useful for simple use-cases where you do not want to deal with listening
  579. * to events and updating the value prop to keep the controlled state in sync.
  580. */
  581. defaultValue?: ?Stringish,
  582. /**
  583. * If `true`, all text will automatically be selected on focus.
  584. */
  585. selectTextOnFocus?: ?boolean,
  586. /**
  587. * If `true`, the text field will blur when submitted.
  588. * The default value is true for single-line fields and false for
  589. * multiline fields. Note that for multiline fields, setting `blurOnSubmit`
  590. * to `true` means that pressing return will blur the field and trigger the
  591. * `onSubmitEditing` event instead of inserting a newline into the field.
  592. */
  593. blurOnSubmit?: ?boolean,
  594. /**
  595. * Note that not all Text styles are supported, an incomplete list of what is not supported includes:
  596. *
  597. * - `borderLeftWidth`
  598. * - `borderTopWidth`
  599. * - `borderRightWidth`
  600. * - `borderBottomWidth`
  601. * - `borderTopLeftRadius`
  602. * - `borderTopRightRadius`
  603. * - `borderBottomRightRadius`
  604. * - `borderBottomLeftRadius`
  605. *
  606. * see [Issue#7070](https://github.com/facebook/react-native/issues/7070)
  607. * for more detail.
  608. *
  609. * [Styles](docs/style.html)
  610. */
  611. style?: ?TextStyleProp,
  612. /**
  613. * If `true`, caret is hidden. The default value is `false`.
  614. * This property is supported only for single-line TextInput component on iOS.
  615. */
  616. caretHidden?: ?boolean,
  617. /*
  618. * If `true`, contextMenuHidden is hidden. The default value is `false`.
  619. */
  620. contextMenuHidden?: ?boolean,
  621. forwardedRef?: ?ReactRefSetter<
  622. React.ElementRef<HostComponent<mixed>> & ImperativeMethods,
  623. >,
  624. |}>;
  625. type ImperativeMethods = $ReadOnly<{|
  626. clear: () => void,
  627. isFocused: () => boolean,
  628. getNativeRef: () => ?React.ElementRef<HostComponent<mixed>>,
  629. |}>;
  630. const emptyFunctionThatReturnsTrue = () => true;
  631. /**
  632. * A foundational component for inputting text into the app via a
  633. * keyboard. Props provide configurability for several features, such as
  634. * auto-correction, auto-capitalization, placeholder text, and different keyboard
  635. * types, such as a numeric keypad.
  636. *
  637. * The simplest use case is to plop down a `TextInput` and subscribe to the
  638. * `onChangeText` events to read the user input. There are also other events,
  639. * such as `onSubmitEditing` and `onFocus` that can be subscribed to. A simple
  640. * example:
  641. *
  642. * ```ReactNativeWebPlayer
  643. * import React, { Component } from 'react';
  644. * import { AppRegistry, TextInput } from 'react-native';
  645. *
  646. * export default class UselessTextInput extends Component {
  647. * constructor(props) {
  648. * super(props);
  649. * this.state = { text: 'Useless Placeholder' };
  650. * }
  651. *
  652. * render() {
  653. * return (
  654. * <TextInput
  655. * style={{height: 40, borderColor: 'gray', borderWidth: 1}}
  656. * onChangeText={(text) => this.setState({text})}
  657. * value={this.state.text}
  658. * />
  659. * );
  660. * }
  661. * }
  662. *
  663. * // skip this line if using Create React Native App
  664. * AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput);
  665. * ```
  666. *
  667. * Two methods exposed via the native element are .focus() and .blur() that
  668. * will focus or blur the TextInput programmatically.
  669. *
  670. * Note that some props are only available with `multiline={true/false}`.
  671. * Additionally, border styles that apply to only one side of the element
  672. * (e.g., `borderBottomColor`, `borderLeftWidth`, etc.) will not be applied if
  673. * `multiline=false`. To achieve the same effect, you can wrap your `TextInput`
  674. * in a `View`:
  675. *
  676. * ```ReactNativeWebPlayer
  677. * import React, { Component } from 'react';
  678. * import { AppRegistry, View, TextInput } from 'react-native';
  679. *
  680. * class UselessTextInput extends Component {
  681. * render() {
  682. * return (
  683. * <TextInput
  684. * {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below
  685. * editable = {true}
  686. * maxLength = {40}
  687. * />
  688. * );
  689. * }
  690. * }
  691. *
  692. * export default class UselessTextInputMultiline extends Component {
  693. * constructor(props) {
  694. * super(props);
  695. * this.state = {
  696. * text: 'Useless Multiline Placeholder',
  697. * };
  698. * }
  699. *
  700. * // If you type something in the text box that is a color, the background will change to that
  701. * // color.
  702. * render() {
  703. * return (
  704. * <View style={{
  705. * backgroundColor: this.state.text,
  706. * borderBottomColor: '#000000',
  707. * borderBottomWidth: 1 }}
  708. * >
  709. * <UselessTextInput
  710. * multiline = {true}
  711. * numberOfLines = {4}
  712. * onChangeText={(text) => this.setState({text})}
  713. * value={this.state.text}
  714. * />
  715. * </View>
  716. * );
  717. * }
  718. * }
  719. *
  720. * // skip these lines if using Create React Native App
  721. * AppRegistry.registerComponent(
  722. * 'AwesomeProject',
  723. * () => UselessTextInputMultiline
  724. * );
  725. * ```
  726. *
  727. * `TextInput` has by default a border at the bottom of its view. This border
  728. * has its padding set by the background image provided by the system, and it
  729. * cannot be changed. Solutions to avoid this is to either not set height
  730. * explicitly, case in which the system will take care of displaying the border
  731. * in the correct position, or to not display the border by setting
  732. * `underlineColorAndroid` to transparent.
  733. *
  734. * Note that on Android performing text selection in input can change
  735. * app's activity `windowSoftInputMode` param to `adjustResize`.
  736. * This may cause issues with components that have position: 'absolute'
  737. * while keyboard is active. To avoid this behavior either specify `windowSoftInputMode`
  738. * in AndroidManifest.xml ( https://developer.android.com/guide/topics/manifest/activity-element.html )
  739. * or control this param programmatically with native code.
  740. *
  741. */
  742. function InternalTextInput(props: Props): React.Node {
  743. const inputRef = useRef<null | React.ElementRef<HostComponent<mixed>>>(null);
  744. // Android sends a "onTextChanged" event followed by a "onSelectionChanged" event, for
  745. // the same "most recent event count".
  746. // For controlled selection, that means that immediately after text is updated,
  747. // a controlled component will pass in the *previous* selection, even if the controlled
  748. // component didn't mean to modify the selection at all.
  749. // Therefore, we ignore selections and pass them through until the selection event has
  750. // been sent.
  751. // Note that this mitigation is NOT needed for Fabric.
  752. let selection: ?Selection =
  753. props.selection == null
  754. ? null
  755. : {
  756. start: props.selection.start,
  757. end: props.selection.end ?? props.selection.start,
  758. };
  759. const [mostRecentEventCount, setMostRecentEventCount] = useState<number>(0);
  760. const [lastNativeText, setLastNativeText] = useState<?Stringish>(props.value);
  761. const [lastNativeSelectionState, setLastNativeSelection] = useState<{|
  762. selection: ?Selection,
  763. mostRecentEventCount: number,
  764. |}>({selection, mostRecentEventCount});
  765. const lastNativeSelection = lastNativeSelectionState.selection;
  766. const lastNativeSelectionEventCount =
  767. lastNativeSelectionState.mostRecentEventCount;
  768. if (lastNativeSelectionEventCount < mostRecentEventCount) {
  769. selection = null;
  770. }
  771. let viewCommands: TextInputNativeCommands<HostComponent<any>>;
  772. if (AndroidTextInputCommands) {
  773. viewCommands = AndroidTextInputCommands;
  774. } else {
  775. viewCommands = props.multiline
  776. ? RCTMultilineTextInputNativeCommands
  777. : RCTSinglelineTextInputNativeCommands;
  778. }
  779. const text =
  780. typeof props.value === 'string'
  781. ? props.value
  782. : typeof props.defaultValue === 'string'
  783. ? props.defaultValue
  784. : '';
  785. // This is necessary in case native updates the text and JS decides
  786. // that the update should be ignored and we should stick with the value
  787. // that we have in JS.
  788. useEffect(() => {
  789. const nativeUpdate = {};
  790. if (lastNativeText !== props.value && typeof props.value === 'string') {
  791. nativeUpdate.text = props.value;
  792. setLastNativeText(props.value);
  793. }
  794. if (
  795. selection &&
  796. lastNativeSelection &&
  797. (lastNativeSelection.start !== selection.start ||
  798. lastNativeSelection.end !== selection.end)
  799. ) {
  800. nativeUpdate.selection = selection;
  801. setLastNativeSelection({selection, mostRecentEventCount});
  802. }
  803. if (Object.keys(nativeUpdate).length === 0) {
  804. return;
  805. }
  806. if (inputRef.current != null) {
  807. viewCommands.setTextAndSelection(
  808. inputRef.current,
  809. mostRecentEventCount,
  810. text,
  811. selection?.start ?? -1,
  812. selection?.end ?? -1,
  813. );
  814. }
  815. }, [
  816. mostRecentEventCount,
  817. inputRef,
  818. props.value,
  819. props.defaultValue,
  820. lastNativeText,
  821. selection,
  822. lastNativeSelection,
  823. text,
  824. viewCommands,
  825. ]);
  826. useEffect(() => {
  827. const inputRefValue = inputRef.current;
  828. if (inputRefValue != null) {
  829. TextInputState.registerInput(inputRefValue);
  830. return () => {
  831. TextInputState.unregisterInput(inputRefValue);
  832. };
  833. }
  834. }, [inputRef]);
  835. useEffect(() => {
  836. // When unmounting we need to blur the input
  837. return () => {
  838. if (isFocused()) {
  839. nullthrows(inputRef.current).blur();
  840. }
  841. };
  842. }, [inputRef]);
  843. function clear(): void {
  844. if (inputRef.current != null) {
  845. viewCommands.setTextAndSelection(
  846. inputRef.current,
  847. mostRecentEventCount,
  848. '',
  849. 0,
  850. 0,
  851. );
  852. }
  853. }
  854. // TODO: Fix this returning true on null === null, when no input is focused
  855. function isFocused(): boolean {
  856. return TextInputState.currentlyFocusedInput() === inputRef.current;
  857. }
  858. function getNativeRef(): ?React.ElementRef<HostComponent<mixed>> {
  859. return inputRef.current;
  860. }
  861. const _setNativeRef = setAndForwardRef({
  862. getForwardedRef: () => props.forwardedRef,
  863. setLocalRef: ref => {
  864. inputRef.current = ref;
  865. /*
  866. Hi reader from the future. I'm sorry for this.
  867. This is a hack. Ideally we would forwardRef to the underlying
  868. host component. However, since TextInput has it's own methods that can be
  869. called as well, if we used the standard forwardRef then these
  870. methods wouldn't be accessible and thus be a breaking change.
  871. We have a couple of options of how to handle this:
  872. - Return a new ref with everything we methods from both. This is problematic
  873. because we need React to also know it is a host component which requires
  874. internals of the class implementation of the ref.
  875. - Break the API and have some other way to call one set of the methods or
  876. the other. This is our long term approach as we want to eventually
  877. get the methods on host components off the ref. So instead of calling
  878. ref.measure() you might call ReactNative.measure(ref). This would hopefully
  879. let the ref for TextInput then have the methods like `.clear`. Or we do it
  880. the other way and make it TextInput.clear(textInputRef) which would be fine
  881. too. Either way though is a breaking change that is longer term.
  882. - Mutate this ref. :( Gross, but accomplishes what we need in the meantime
  883. before we can get to the long term breaking change.
  884. */
  885. if (ref) {
  886. ref.clear = clear;
  887. ref.isFocused = isFocused;
  888. ref.getNativeRef = getNativeRef;
  889. }
  890. },
  891. });
  892. const _onPress = (event: PressEvent) => {
  893. if (props.editable || props.editable === undefined) {
  894. nullthrows(inputRef.current).focus();
  895. }
  896. };
  897. const _onChange = (event: ChangeEvent) => {
  898. const text = event.nativeEvent.text;
  899. props.onChange && props.onChange(event);
  900. props.onChangeText && props.onChangeText(text);
  901. if (inputRef.current == null) {
  902. // calling `props.onChange` or `props.onChangeText`
  903. // may clean up the input itself. Exits here.
  904. return;
  905. }
  906. setLastNativeText(text);
  907. // This must happen last, after we call setLastNativeText.
  908. // Different ordering can cause bugs when editing AndroidTextInputs
  909. // with multiple Fragments.
  910. // We must update this so that controlled input updates work.
  911. setMostRecentEventCount(event.nativeEvent.eventCount);
  912. };
  913. const _onSelectionChange = (event: SelectionChangeEvent) => {
  914. props.onSelectionChange && props.onSelectionChange(event);
  915. if (inputRef.current == null) {
  916. // calling `props.onSelectionChange`
  917. // may clean up the input itself. Exits here.
  918. return;
  919. }
  920. setLastNativeSelection({
  921. selection: event.nativeEvent.selection,
  922. mostRecentEventCount,
  923. });
  924. };
  925. const _onFocus = (event: FocusEvent) => {
  926. TextInputState.focusInput(inputRef.current);
  927. if (props.onFocus) {
  928. props.onFocus(event);
  929. }
  930. };
  931. const _onBlur = (event: BlurEvent) => {
  932. TextInputState.blurInput(inputRef.current);
  933. if (props.onBlur) {
  934. props.onBlur(event);
  935. }
  936. };
  937. const _onScroll = (event: ScrollEvent) => {
  938. props.onScroll && props.onScroll(event);
  939. };
  940. let textInput = null;
  941. let additionalTouchableProps: {|
  942. rejectResponderTermination?: $PropertyType<
  943. Props,
  944. 'rejectResponderTermination',
  945. >,
  946. // This is a hack to let Flow know we want an exact object
  947. |} = {...null};
  948. if (Platform.OS === 'ios') {
  949. const RCTTextInputView = props.multiline
  950. ? RCTMultilineTextInputView
  951. : RCTSinglelineTextInputView;
  952. const style = props.multiline
  953. ? [styles.multilineInput, props.style]
  954. : props.style;
  955. additionalTouchableProps.rejectResponderTermination =
  956. props.rejectResponderTermination;
  957. textInput = (
  958. <RCTTextInputView
  959. ref={_setNativeRef}
  960. {...props}
  961. dataDetectorTypes={props.dataDetectorTypes}
  962. mostRecentEventCount={mostRecentEventCount}
  963. onBlur={_onBlur}
  964. onChange={_onChange}
  965. onContentSizeChange={props.onContentSizeChange}
  966. onFocus={_onFocus}
  967. onScroll={_onScroll}
  968. onSelectionChange={_onSelectionChange}
  969. onSelectionChangeShouldSetResponder={emptyFunctionThatReturnsTrue}
  970. selection={selection}
  971. style={style}
  972. text={text}
  973. />
  974. );
  975. } else if (Platform.OS === 'android') {
  976. const style = [props.style];
  977. const autoCapitalize = props.autoCapitalize || 'sentences';
  978. let children = props.children;
  979. let childCount = 0;
  980. React.Children.forEach(children, () => ++childCount);
  981. invariant(
  982. !(props.value && childCount),
  983. 'Cannot specify both value and children.',
  984. );
  985. if (childCount > 1) {
  986. children = <Text>{children}</Text>;
  987. }
  988. textInput = (
  989. /* $FlowFixMe the types for AndroidTextInput don't match up exactly with
  990. the props for TextInput. This will need to get fixed */
  991. <AndroidTextInput
  992. ref={_setNativeRef}
  993. {...props}
  994. autoCapitalize={autoCapitalize}
  995. children={children}
  996. disableFullscreenUI={props.disableFullscreenUI}
  997. mostRecentEventCount={mostRecentEventCount}
  998. onBlur={_onBlur}
  999. onChange={_onChange}
  1000. onFocus={_onFocus}
  1001. /* $FlowFixMe the types for AndroidTextInput don't match up exactly
  1002. * with the props for TextInput. This will need to get fixed */
  1003. onScroll={_onScroll}
  1004. onSelectionChange={_onSelectionChange}
  1005. selection={selection}
  1006. style={style}
  1007. text={text}
  1008. textBreakStrategy={props.textBreakStrategy}
  1009. />
  1010. );
  1011. }
  1012. return (
  1013. <TextAncestor.Provider value={true}>
  1014. <TouchableWithoutFeedback
  1015. onLayout={props.onLayout}
  1016. onPress={_onPress}
  1017. accessible={props.accessible}
  1018. accessibilityLabel={props.accessibilityLabel}
  1019. accessibilityRole={props.accessibilityRole}
  1020. accessibilityState={props.accessibilityState}
  1021. nativeID={props.nativeID}
  1022. testID={props.testID}
  1023. {...additionalTouchableProps}>
  1024. {textInput}
  1025. </TouchableWithoutFeedback>
  1026. </TextAncestor.Provider>
  1027. );
  1028. }
  1029. const ExportedForwardRef: React.AbstractComponent<
  1030. React.ElementConfig<typeof InternalTextInput>,
  1031. React.ElementRef<HostComponent<mixed>> & ImperativeMethods,
  1032. > = React.forwardRef(function TextInput(
  1033. props,
  1034. forwardedRef: ReactRefSetter<
  1035. React.ElementRef<HostComponent<mixed>> & ImperativeMethods,
  1036. >,
  1037. ) {
  1038. return <InternalTextInput {...props} forwardedRef={forwardedRef} />;
  1039. });
  1040. // $FlowFixMe
  1041. ExportedForwardRef.defaultProps = {
  1042. allowFontScaling: true,
  1043. rejectResponderTermination: true,
  1044. underlineColorAndroid: 'transparent',
  1045. };
  1046. // TODO: Deprecate this
  1047. // $FlowFixMe
  1048. ExportedForwardRef.propTypes = DeprecatedTextInputPropTypes;
  1049. // $FlowFixMe
  1050. ExportedForwardRef.State = {
  1051. currentlyFocusedInput: TextInputState.currentlyFocusedInput,
  1052. currentlyFocusedField: TextInputState.currentlyFocusedField,
  1053. focusTextInput: TextInputState.focusTextInput,
  1054. blurTextInput: TextInputState.blurTextInput,
  1055. };
  1056. type TextInputComponentStatics = $ReadOnly<{|
  1057. State: $ReadOnly<{|
  1058. currentlyFocusedInput: typeof TextInputState.currentlyFocusedInput,
  1059. currentlyFocusedField: typeof TextInputState.currentlyFocusedField,
  1060. focusTextInput: typeof TextInputState.focusTextInput,
  1061. blurTextInput: typeof TextInputState.blurTextInput,
  1062. |}>,
  1063. propTypes: typeof DeprecatedTextInputPropTypes,
  1064. |}>;
  1065. const styles = StyleSheet.create({
  1066. multilineInput: {
  1067. // This default top inset makes RCTMultilineTextInputView seem as close as possible
  1068. // to single-line RCTSinglelineTextInputView defaults, using the system defaults
  1069. // of font size 17 and a height of 31 points.
  1070. paddingTop: 5,
  1071. },
  1072. });
  1073. module.exports = ((ExportedForwardRef: any): React.AbstractComponent<
  1074. React.ElementConfig<typeof InternalTextInput>,
  1075. $ReadOnly<{|
  1076. ...React.ElementRef<HostComponent<mixed>>,
  1077. ...ImperativeMethods,
  1078. |}>,
  1079. > &
  1080. TextInputComponentStatics);