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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. autoFocus = { true }
  145. onChangeText = { this._onTypeQuery }
  146. placeholder = {
  147. this.props.t(`inviteDialog.${placeholderKey}`)
  148. }
  149. ref = { this._setFieldRef }
  150. style = { styles.searchField } />
  151. </View>
  152. <FlatList
  153. ItemSeparatorComponent = { this._renderSeparator }
  154. data = { this.state.selectableItems }
  155. extraData = { inviteItems }
  156. keyExtractor = { this._keyExtractor }
  157. keyboardShouldPersistTaps = 'always'
  158. renderItem = { this._renderItem }
  159. style = { styles.resultList } />
  160. </SafeAreaView>
  161. </Modal>
  162. );
  163. }
  164. /**
  165. * Clears the dialog content.
  166. *
  167. * @returns {void}
  168. */
  169. _clearState() {
  170. this.setState(this.defaultState);
  171. }
  172. _invite: Array<Object> => Promise<Array<Object>>
  173. _isAddDisabled: () => boolean;
  174. _keyExtractor: Object => string
  175. /**
  176. * Key extractor for the flatlist.
  177. *
  178. * @param {Object} item - The flatlist item that we need the key to be
  179. * generated for.
  180. * @returns {string}
  181. */
  182. _keyExtractor(item) {
  183. return item.type === 'user' ? item.user_id : item.number;
  184. }
  185. _onCloseAddPeopleDialog: () => void
  186. /**
  187. * Closes the dialog.
  188. *
  189. * @returns {void}
  190. */
  191. _onCloseAddPeopleDialog() {
  192. this.props.dispatch(setAddPeopleDialogVisible(false));
  193. }
  194. _onInvite: () => void
  195. /**
  196. * Invites the selected entries.
  197. *
  198. * @returns {void}
  199. */
  200. _onInvite() {
  201. this._invite(this.state.inviteItems)
  202. .then(invitesLeftToSend => {
  203. if (invitesLeftToSend.length) {
  204. this.setState({
  205. inviteItems: invitesLeftToSend
  206. });
  207. this._showFailedInviteAlert();
  208. } else {
  209. this._onCloseAddPeopleDialog();
  210. }
  211. });
  212. }
  213. _onPressItem: Item => Function
  214. /**
  215. * Function to preapre a callback for the onPress event of the touchable.
  216. *
  217. * @param {Item} item - The item on which onPress was invoked.
  218. * @returns {Function}
  219. */
  220. _onPressItem(item) {
  221. return () => {
  222. const { inviteItems } = this.state;
  223. const finderKey = item.type === 'phone' ? 'number' : 'user_id';
  224. if (inviteItems.find(
  225. _.matchesProperty(finderKey, item[finderKey]))) {
  226. // Item is already selected, need to unselect it.
  227. this.setState({
  228. inviteItems: inviteItems.filter(
  229. element => item[finderKey] !== element[finderKey])
  230. });
  231. } else {
  232. // Item is not selected yet, need to add to the list.
  233. const items: Array<*> = inviteItems.concat(item);
  234. this.setState({
  235. inviteItems: _.sortBy(items, [ 'name', 'number' ])
  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. selectableItems = _.sortBy(selectableItems, [ 'name', 'number' ]);
  281. this.setState({
  282. selectableItems: this.state.inviteItems.concat(selectableItems)
  283. });
  284. })
  285. .finally(() => {
  286. this.setState({
  287. searchInprogress: false
  288. }, () => {
  289. this.inputFieldRef && this.inputFieldRef.focus();
  290. });
  291. });
  292. }
  293. _query: (string) => Promise<Array<Object>>;
  294. _renderItem: Object => ?React$Element<*>
  295. /**
  296. * Renders a single item in the {@code FlatList}.
  297. *
  298. * @param {Object} flatListItem - An item of the data array of the
  299. * {@code FlatList}.
  300. * @param {number} index - The index of the currently rendered item.
  301. * @returns {?React$Element<*>}
  302. */
  303. _renderItem(flatListItem, index) {
  304. const { item } = flatListItem;
  305. const { inviteItems } = this.state;
  306. let selected = false;
  307. let renderableItem;
  308. switch (item.type) {
  309. case 'phone':
  310. selected
  311. = inviteItems.find(_.matchesProperty('number', item.number));
  312. renderableItem = {
  313. avatar: 'phone',
  314. key: item.number,
  315. title: item.number
  316. };
  317. break;
  318. case 'user':
  319. selected
  320. = inviteItems.find(_.matchesProperty('user_id', item.user_id));
  321. renderableItem = {
  322. avatar: item.avatar,
  323. key: item.user_id,
  324. title: item.name
  325. };
  326. break;
  327. default:
  328. return null;
  329. }
  330. return (
  331. <TouchableOpacity onPress = { this._onPressItem(item) } >
  332. <View
  333. pointerEvents = 'box-only'
  334. style = { styles.itemWrapper }>
  335. <Icon
  336. name = { selected
  337. ? 'radio_button_checked'
  338. : 'radio_button_unchecked' }
  339. style = { styles.radioButton } />
  340. <AvatarListItem
  341. avatarSize = { AVATAR_SIZE }
  342. avatarStyle = { styles.avatar }
  343. avatarTextStyle = { styles.avatarText }
  344. item = { renderableItem }
  345. key = { index }
  346. linesStyle = { styles.itemLinesStyle }
  347. titleStyle = { styles.itemText } />
  348. </View>
  349. </TouchableOpacity>
  350. );
  351. }
  352. _renderSeparator: () => React$Element<*> | null
  353. /**
  354. * Renders the item separator.
  355. *
  356. * @returns {?React$Element<*>}
  357. */
  358. _renderSeparator() {
  359. return (
  360. <View style = { styles.separator } />
  361. );
  362. }
  363. _setFieldRef: ?TextInput => void
  364. /**
  365. * Sets a reference to the input field for later use.
  366. *
  367. * @param {?TextInput} input - The reference to the input field.
  368. * @returns {void}
  369. */
  370. _setFieldRef(input) {
  371. this.inputFieldRef = input;
  372. }
  373. /**
  374. * Shows an alert telling the user that some invitees were failed to be
  375. * invited.
  376. *
  377. * NOTE: We're using an Alert here because we're on a modal and it makes
  378. * using our dialogs a tad more difficult.
  379. *
  380. * @returns {void}
  381. */
  382. _showFailedInviteAlert() {
  383. const { t } = this.props;
  384. Alert.alert(
  385. t('inviteDialog.alertTitle'),
  386. t('inviteDialog.alertText'),
  387. [
  388. {
  389. text: t('inviteDialog.alertOk')
  390. }
  391. ]
  392. );
  393. }
  394. }
  395. /**
  396. * Maps part of the Redux state to the props of this component.
  397. *
  398. * @param {Object} state - The Redux state.
  399. * @returns {{
  400. * _isVisible: boolean
  401. * }}
  402. */
  403. function _mapStateToProps(state: Object) {
  404. return {
  405. ..._abstractMapStateToProps(state),
  406. _isVisible: state['features/invite'].inviteDialogVisible
  407. };
  408. }
  409. export default translate(connect(_mapStateToProps)(AddPeopleDialog));