You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AddPeopleDialog.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. // @flow
  2. import _ from 'lodash';
  3. import React from 'react';
  4. import {
  5. ActivityIndicator,
  6. FlatList,
  7. KeyboardAvoidingView,
  8. Platform,
  9. SafeAreaView,
  10. TextInput,
  11. TouchableOpacity,
  12. View
  13. } from 'react-native';
  14. import { AlertDialog, openDialog } from '../../../../base/dialog';
  15. import { Icon } from '../../../../base/font-icons';
  16. import { translate } from '../../../../base/i18n';
  17. import {
  18. AvatarListItem,
  19. HeaderWithNavigation,
  20. SlidingView,
  21. type Item
  22. } from '../../../../base/react';
  23. import { connect } from '../../../../base/redux';
  24. import { setAddPeopleDialogVisible } from '../../../actions';
  25. import AbstractAddPeopleDialog, {
  26. type Props as AbstractProps,
  27. type State as AbstractState,
  28. _mapStateToProps as _abstractMapStateToProps
  29. } from '../AbstractAddPeopleDialog';
  30. import styles, {
  31. AVATAR_SIZE,
  32. DARK_GREY
  33. } from './styles';
  34. type Props = AbstractProps & {
  35. /**
  36. * True if the invite dialog should be open, false otherwise.
  37. */
  38. _isVisible: boolean,
  39. /**
  40. * Function used to translate i18n labels.
  41. */
  42. t: Function
  43. };
  44. type State = AbstractState & {
  45. /**
  46. * State variable to keep track of the search field value.
  47. */
  48. fieldValue: string,
  49. /**
  50. * True if a search is in progress, false otherwise.
  51. */
  52. searchInprogress: boolean,
  53. /**
  54. * An array of items that are selectable on this dialog. This is usually
  55. * populated by an async search.
  56. */
  57. selectableItems: Array<Object>
  58. };
  59. /**
  60. * Implements a special dialog to invite people from a directory service.
  61. */
  62. class AddPeopleDialog extends AbstractAddPeopleDialog<Props, State> {
  63. /**
  64. * Default state object to reset the state to when needed.
  65. */
  66. defaultState = {
  67. addToCallError: false,
  68. addToCallInProgress: false,
  69. fieldValue: '',
  70. inviteItems: [],
  71. searchInprogress: false,
  72. selectableItems: []
  73. };
  74. /**
  75. * Ref of the search field.
  76. */
  77. inputFieldRef: ?TextInput;
  78. /**
  79. * TimeoutID to delay the search for the time the user is probably typing.
  80. */
  81. searchTimeout: TimeoutID;
  82. /**
  83. * Contrustor of the component.
  84. *
  85. * @inheritdoc
  86. */
  87. constructor(props: Props) {
  88. super(props);
  89. this.state = this.defaultState;
  90. this._keyExtractor = this._keyExtractor.bind(this);
  91. this._renderItem = this._renderItem.bind(this);
  92. this._renderSeparator = this._renderSeparator.bind(this);
  93. this._onClearField = this._onClearField.bind(this);
  94. this._onCloseAddPeopleDialog = this._onCloseAddPeopleDialog.bind(this);
  95. this._onInvite = this._onInvite.bind(this);
  96. this._onPressItem = this._onPressItem.bind(this);
  97. this._onTypeQuery = this._onTypeQuery.bind(this);
  98. this._setFieldRef = this._setFieldRef.bind(this);
  99. }
  100. /**
  101. * Implements {@code Component#componentDidUpdate}.
  102. *
  103. * @inheritdoc
  104. */
  105. componentDidUpdate(prevProps) {
  106. if (prevProps._isVisible !== this.props._isVisible) {
  107. // Clear state
  108. this._clearState();
  109. }
  110. }
  111. /**
  112. * Implements {@code Component#render}.
  113. *
  114. * @inheritdoc
  115. */
  116. render() {
  117. const {
  118. _addPeopleEnabled,
  119. _dialOutEnabled
  120. } = this.props;
  121. const { inviteItems } = this.state;
  122. let placeholderKey = 'searchPlaceholder';
  123. if (!_addPeopleEnabled) {
  124. placeholderKey = 'searchCallOnlyPlaceholder';
  125. } else if (!_dialOutEnabled) {
  126. placeholderKey = 'searchPeopleOnlyPlaceholder';
  127. }
  128. return (
  129. <SlidingView
  130. onHide = { this._onCloseAddPeopleDialog }
  131. position = 'bottom'
  132. show = { this.props._isVisible } >
  133. <HeaderWithNavigation
  134. forwardDisabled = { this._isAddDisabled() }
  135. forwardLabelKey = 'inviteDialog.send'
  136. headerLabelKey = 'inviteDialog.header'
  137. onPressBack = { this._onCloseAddPeopleDialog }
  138. onPressForward = { this._onInvite } />
  139. <KeyboardAvoidingView
  140. behavior = 'padding'
  141. style = { styles.avoidingView }>
  142. <SafeAreaView style = { styles.dialogWrapper }>
  143. <View
  144. style = { styles.searchFieldWrapper }>
  145. <View style = { styles.searchIconWrapper }>
  146. { this.state.searchInprogress
  147. ? <ActivityIndicator
  148. color = { DARK_GREY }
  149. size = 'small' />
  150. : <Icon
  151. name = { 'search' }
  152. style = { styles.searchIcon } />}
  153. </View>
  154. <TextInput
  155. autoCorrect = { false }
  156. autoFocus = { true }
  157. clearButtonMode = 'always' // iOS only
  158. onChangeText = { this._onTypeQuery }
  159. placeholder = {
  160. this.props.t(`inviteDialog.${placeholderKey}`)
  161. }
  162. ref = { this._setFieldRef }
  163. style = { styles.searchField }
  164. value = { this.state.fieldValue } />
  165. { this._renderAndroidClearButton() }
  166. </View>
  167. <FlatList
  168. ItemSeparatorComponent = { this._renderSeparator }
  169. data = { this.state.selectableItems }
  170. extraData = { inviteItems }
  171. keyExtractor = { this._keyExtractor }
  172. keyboardShouldPersistTaps = 'always'
  173. renderItem = { this._renderItem }
  174. style = { styles.resultList } />
  175. </SafeAreaView>
  176. </KeyboardAvoidingView>
  177. </SlidingView>
  178. );
  179. }
  180. /**
  181. * Clears the dialog content.
  182. *
  183. * @returns {void}
  184. */
  185. _clearState() {
  186. this.setState(this.defaultState);
  187. }
  188. _invite: Array<Object> => Promise<Array<Object>>
  189. _isAddDisabled: () => boolean;
  190. _keyExtractor: Object => string
  191. /**
  192. * Key extractor for the flatlist.
  193. *
  194. * @param {Object} item - The flatlist item that we need the key to be
  195. * generated for.
  196. * @returns {string}
  197. */
  198. _keyExtractor(item) {
  199. return item.type === 'user' ? item.id || item.user_id : item.number;
  200. }
  201. _onClearField: () => void
  202. /**
  203. * Callback to clear the text field.
  204. *
  205. * @returns {void}
  206. */
  207. _onClearField() {
  208. this.setState({
  209. fieldValue: ''
  210. });
  211. // Clear search results
  212. this._onTypeQuery('');
  213. }
  214. _onCloseAddPeopleDialog: () => boolean
  215. /**
  216. * Closes the dialog.
  217. *
  218. * @returns {boolean}
  219. */
  220. _onCloseAddPeopleDialog() {
  221. if (this.props._isVisible) {
  222. this.props.dispatch(setAddPeopleDialogVisible(false));
  223. return true;
  224. }
  225. return false;
  226. }
  227. _onInvite: () => void
  228. /**
  229. * Invites the selected entries.
  230. *
  231. * @returns {void}
  232. */
  233. _onInvite() {
  234. this._invite(this.state.inviteItems)
  235. .then(invitesLeftToSend => {
  236. if (invitesLeftToSend.length) {
  237. this.setState({
  238. inviteItems: invitesLeftToSend
  239. });
  240. this._showFailedInviteAlert();
  241. } else {
  242. this._onCloseAddPeopleDialog();
  243. }
  244. });
  245. }
  246. _onPressItem: Item => Function
  247. /**
  248. * Function to preapre a callback for the onPress event of the touchable.
  249. *
  250. * @param {Item} item - The item on which onPress was invoked.
  251. * @returns {Function}
  252. */
  253. _onPressItem(item) {
  254. return () => {
  255. const { inviteItems } = this.state;
  256. const finderKey = item.type === 'phone' ? 'number' : 'user_id';
  257. if (inviteItems.find(
  258. _.matchesProperty(finderKey, item[finderKey]))) {
  259. // Item is already selected, need to unselect it.
  260. this.setState({
  261. inviteItems: inviteItems.filter(
  262. element => item[finderKey] !== element[finderKey])
  263. });
  264. } else {
  265. // Item is not selected yet, need to add to the list.
  266. const items: Array<*> = inviteItems.concat(item);
  267. this.setState({
  268. inviteItems: _.sortBy(items, [ 'name', 'number' ])
  269. });
  270. }
  271. };
  272. }
  273. _onTypeQuery: string => void
  274. /**
  275. * Handles the typing event of the text field on the dialog and performs the
  276. * search.
  277. *
  278. * @param {string} query - The query that is typed in the field.
  279. * @returns {void}
  280. */
  281. _onTypeQuery(query) {
  282. this.setState({
  283. fieldValue: query
  284. });
  285. clearTimeout(this.searchTimeout);
  286. this.searchTimeout = setTimeout(() => {
  287. this.setState({
  288. searchInprogress: true
  289. }, () => {
  290. this._performSearch(query);
  291. });
  292. }, 500);
  293. }
  294. /**
  295. * Performs the actual search.
  296. *
  297. * @param {string} query - The query to search for.
  298. * @returns {void}
  299. */
  300. _performSearch(query) {
  301. this._query(query).then(results => {
  302. const { inviteItems } = this.state;
  303. let selectableItems = results.filter(result => {
  304. switch (result.type) {
  305. case 'phone':
  306. return result.allowed && result.number
  307. && !inviteItems.find(
  308. _.matchesProperty('number', result.number));
  309. case 'user':
  310. return !inviteItems.find(
  311. (result.user_id && _.matchesProperty('id', result.id))
  312. || (result.user_id && _.matchesProperty('user_id', result.user_id)));
  313. default:
  314. return false;
  315. }
  316. });
  317. selectableItems = _.sortBy(selectableItems, [ 'name', 'number' ]);
  318. this.setState({
  319. selectableItems: this.state.inviteItems.concat(selectableItems)
  320. });
  321. })
  322. .finally(() => {
  323. this.setState({
  324. searchInprogress: false
  325. }, () => {
  326. this.inputFieldRef && this.inputFieldRef.focus();
  327. });
  328. });
  329. }
  330. _query: (string) => Promise<Array<Object>>;
  331. _renderItem: Object => ?React$Element<*>
  332. /**
  333. * Renders a button to clear the text field on Android.
  334. *
  335. * NOTE: For the best platform experience we use the native solution on iOS.
  336. *
  337. * @returns {React#Element<*>}
  338. */
  339. _renderAndroidClearButton() {
  340. if (Platform.OS !== 'android' || !this.state.fieldValue.length) {
  341. return null;
  342. }
  343. return (
  344. <TouchableOpacity
  345. onPress = { this._onClearField }
  346. style = { styles.clearButton }>
  347. <View style = { styles.clearIconContainer }>
  348. <Icon
  349. name = 'close'
  350. style = { styles.clearIcon } />
  351. </View>
  352. </TouchableOpacity>
  353. );
  354. }
  355. /**
  356. * Renders a single item in the {@code FlatList}.
  357. *
  358. * @param {Object} flatListItem - An item of the data array of the
  359. * {@code FlatList}.
  360. * @param {number} index - The index of the currently rendered item.
  361. * @returns {?React$Element<*>}
  362. */
  363. _renderItem(flatListItem, index) {
  364. const { item } = flatListItem;
  365. const { inviteItems } = this.state;
  366. let selected = false;
  367. let renderableItem;
  368. switch (item.type) {
  369. case 'phone':
  370. selected
  371. = inviteItems.find(_.matchesProperty('number', item.number));
  372. renderableItem = {
  373. avatar: 'icon://phone',
  374. key: item.number,
  375. title: item.number
  376. };
  377. break;
  378. case 'user':
  379. selected
  380. = item.id
  381. ? inviteItems.find(_.matchesProperty('id', item.id))
  382. : inviteItems.find(_.matchesProperty('user_id', item.user_id));
  383. renderableItem = {
  384. avatar: item.avatar,
  385. key: item.id || item.user_id,
  386. title: item.name
  387. };
  388. break;
  389. default:
  390. return null;
  391. }
  392. return (
  393. <TouchableOpacity onPress = { this._onPressItem(item) } >
  394. <View
  395. pointerEvents = 'box-only'
  396. style = { styles.itemWrapper }>
  397. <Icon
  398. name = { selected
  399. ? 'radio_button_checked'
  400. : 'radio_button_unchecked' }
  401. style = { styles.radioButton } />
  402. <AvatarListItem
  403. avatarSize = { AVATAR_SIZE }
  404. avatarStyle = { styles.avatar }
  405. avatarTextStyle = { styles.avatarText }
  406. item = { renderableItem }
  407. key = { index }
  408. linesStyle = { styles.itemLinesStyle }
  409. titleStyle = { styles.itemText } />
  410. </View>
  411. </TouchableOpacity>
  412. );
  413. }
  414. _renderSeparator: () => React$Element<*> | null
  415. /**
  416. * Renders the item separator.
  417. *
  418. * @returns {?React$Element<*>}
  419. */
  420. _renderSeparator() {
  421. return (
  422. <View style = { styles.separator } />
  423. );
  424. }
  425. _setFieldRef: ?TextInput => void
  426. /**
  427. * Sets a reference to the input field for later use.
  428. *
  429. * @param {?TextInput} input - The reference to the input field.
  430. * @returns {void}
  431. */
  432. _setFieldRef(input) {
  433. this.inputFieldRef = input;
  434. }
  435. /**
  436. * Shows an alert telling the user that some invitees were failed to be
  437. * invited.
  438. *
  439. * NOTE: We're using an Alert here because we're on a modal and it makes
  440. * using our dialogs a tad more difficult.
  441. *
  442. * @returns {void}
  443. */
  444. _showFailedInviteAlert() {
  445. this.props.dispatch(openDialog(AlertDialog, {
  446. contentKey: {
  447. key: 'inviteDialog.alertText'
  448. }
  449. }));
  450. }
  451. }
  452. /**
  453. * Maps part of the Redux state to the props of this component.
  454. *
  455. * @param {Object} state - The Redux state.
  456. * @returns {{
  457. * _isVisible: boolean
  458. * }}
  459. */
  460. function _mapStateToProps(state: Object) {
  461. return {
  462. ..._abstractMapStateToProps(state),
  463. _isVisible: state['features/invite'].inviteDialogVisible
  464. };
  465. }
  466. export default translate(connect(_mapStateToProps)(AddPeopleDialog));