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

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