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

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