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 13KB

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