您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

AddPeopleDialog.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // @flow
  2. import _ from 'lodash';
  3. import React from 'react';
  4. import {
  5. ActivityIndicator,
  6. Alert,
  7. FlatList,
  8. KeyboardAvoidingView,
  9. Platform,
  10. SafeAreaView,
  11. TextInput,
  12. TouchableOpacity,
  13. View
  14. } from 'react-native';
  15. import { Icon } from '../../../../base/font-icons';
  16. import { translate } from '../../../../base/i18n';
  17. import {
  18. AvatarListItem,
  19. HeaderWithNavigation,
  20. Modal,
  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. <Modal
  130. onRequestClose = { this._onCloseAddPeopleDialog }
  131. visible = { this.props._isVisible }>
  132. <HeaderWithNavigation
  133. forwardDisabled = { this._isAddDisabled() }
  134. forwardLabelKey = 'inviteDialog.send'
  135. headerLabelKey = 'inviteDialog.header'
  136. onPressBack = { this._onCloseAddPeopleDialog }
  137. onPressForward = { this._onInvite } />
  138. <KeyboardAvoidingView
  139. behavior = 'padding'
  140. style = { styles.avoidingView }>
  141. <SafeAreaView style = { styles.dialogWrapper }>
  142. <View
  143. style = { styles.searchFieldWrapper }>
  144. <View style = { styles.searchIconWrapper }>
  145. { this.state.searchInprogress
  146. ? <ActivityIndicator
  147. color = { DARK_GREY }
  148. size = 'small' />
  149. : <Icon
  150. name = { 'search' }
  151. style = { styles.searchIcon } />}
  152. </View>
  153. <TextInput
  154. autoCorrect = { false }
  155. autoFocus = { true }
  156. clearButtonMode = 'always' // iOS only
  157. onChangeText = { this._onTypeQuery }
  158. placeholder = {
  159. this.props.t(`inviteDialog.${placeholderKey}`)
  160. }
  161. ref = { this._setFieldRef }
  162. style = { styles.searchField }
  163. value = { this.state.fieldValue } />
  164. { this._renderAndroidClearButton() }
  165. </View>
  166. <FlatList
  167. ItemSeparatorComponent = { this._renderSeparator }
  168. data = { this.state.selectableItems }
  169. extraData = { inviteItems }
  170. keyExtractor = { this._keyExtractor }
  171. keyboardShouldPersistTaps = 'always'
  172. renderItem = { this._renderItem }
  173. style = { styles.resultList } />
  174. </SafeAreaView>
  175. </KeyboardAvoidingView>
  176. </Modal>
  177. );
  178. }
  179. /**
  180. * Clears the dialog content.
  181. *
  182. * @returns {void}
  183. */
  184. _clearState() {
  185. this.setState(this.defaultState);
  186. }
  187. _invite: Array<Object> => Promise<Array<Object>>
  188. _isAddDisabled: () => boolean;
  189. _keyExtractor: Object => string
  190. /**
  191. * Key extractor for the flatlist.
  192. *
  193. * @param {Object} item - The flatlist item that we need the key to be
  194. * generated for.
  195. * @returns {string}
  196. */
  197. _keyExtractor(item) {
  198. return item.type === 'user' ? item.id || item.user_id : item.number;
  199. }
  200. _onClearField: () => void
  201. /**
  202. * Callback to clear the text field.
  203. *
  204. * @returns {void}
  205. */
  206. _onClearField() {
  207. this.setState({
  208. fieldValue: ''
  209. });
  210. // Clear search results
  211. this._onTypeQuery('');
  212. }
  213. _onCloseAddPeopleDialog: () => void
  214. /**
  215. * Closes the dialog.
  216. *
  217. * @returns {void}
  218. */
  219. _onCloseAddPeopleDialog() {
  220. this.props.dispatch(setAddPeopleDialogVisible(false));
  221. }
  222. _onInvite: () => void
  223. /**
  224. * Invites the selected entries.
  225. *
  226. * @returns {void}
  227. */
  228. _onInvite() {
  229. this._invite(this.state.inviteItems)
  230. .then(invitesLeftToSend => {
  231. if (invitesLeftToSend.length) {
  232. this.setState({
  233. inviteItems: invitesLeftToSend
  234. });
  235. this._showFailedInviteAlert();
  236. } else {
  237. this._onCloseAddPeopleDialog();
  238. }
  239. });
  240. }
  241. _onPressItem: Item => Function
  242. /**
  243. * Function to preapre a callback for the onPress event of the touchable.
  244. *
  245. * @param {Item} item - The item on which onPress was invoked.
  246. * @returns {Function}
  247. */
  248. _onPressItem(item) {
  249. return () => {
  250. const { inviteItems } = this.state;
  251. const finderKey = item.type === 'phone' ? 'number' : 'user_id';
  252. if (inviteItems.find(
  253. _.matchesProperty(finderKey, item[finderKey]))) {
  254. // Item is already selected, need to unselect it.
  255. this.setState({
  256. inviteItems: inviteItems.filter(
  257. element => item[finderKey] !== element[finderKey])
  258. });
  259. } else {
  260. // Item is not selected yet, need to add to the list.
  261. const items: Array<*> = inviteItems.concat(item);
  262. this.setState({
  263. inviteItems: _.sortBy(items, [ 'name', 'number' ])
  264. });
  265. }
  266. };
  267. }
  268. _onTypeQuery: string => void
  269. /**
  270. * Handles the typing event of the text field on the dialog and performs the
  271. * search.
  272. *
  273. * @param {string} query - The query that is typed in the field.
  274. * @returns {void}
  275. */
  276. _onTypeQuery(query) {
  277. this.setState({
  278. fieldValue: query
  279. });
  280. clearTimeout(this.searchTimeout);
  281. this.searchTimeout = setTimeout(() => {
  282. this.setState({
  283. searchInprogress: true
  284. }, () => {
  285. this._performSearch(query);
  286. });
  287. }, 500);
  288. }
  289. /**
  290. * Performs the actual search.
  291. *
  292. * @param {string} query - The query to search for.
  293. * @returns {void}
  294. */
  295. _performSearch(query) {
  296. this._query(query).then(results => {
  297. const { inviteItems } = this.state;
  298. let selectableItems = results.filter(result => {
  299. switch (result.type) {
  300. case 'phone':
  301. return result.allowed && result.number
  302. && !inviteItems.find(
  303. _.matchesProperty('number', result.number));
  304. case 'user':
  305. return !inviteItems.find(
  306. (result.user_id && _.matchesProperty('id', result.id))
  307. || (result.user_id && _.matchesProperty('user_id', result.user_id)));
  308. default:
  309. return false;
  310. }
  311. });
  312. selectableItems = _.sortBy(selectableItems, [ 'name', 'number' ]);
  313. this.setState({
  314. selectableItems: this.state.inviteItems.concat(selectableItems)
  315. });
  316. })
  317. .finally(() => {
  318. this.setState({
  319. searchInprogress: false
  320. }, () => {
  321. this.inputFieldRef && this.inputFieldRef.focus();
  322. });
  323. });
  324. }
  325. _query: (string) => Promise<Array<Object>>;
  326. _renderItem: Object => ?React$Element<*>
  327. /**
  328. * Renders a button to clear the text field on Android.
  329. *
  330. * NOTE: For the best platform experience we use the native solution on iOS.
  331. *
  332. * @returns {React#Element<*>}
  333. */
  334. _renderAndroidClearButton() {
  335. if (Platform.OS !== 'android' || !this.state.fieldValue.length) {
  336. return null;
  337. }
  338. return (
  339. <TouchableOpacity
  340. onPress = { this._onClearField }
  341. style = { styles.clearButton }>
  342. <View style = { styles.clearIconContainer }>
  343. <Icon
  344. name = 'close'
  345. style = { styles.clearIcon } />
  346. </View>
  347. </TouchableOpacity>
  348. );
  349. }
  350. /**
  351. * Renders a single item in the {@code FlatList}.
  352. *
  353. * @param {Object} flatListItem - An item of the data array of the
  354. * {@code FlatList}.
  355. * @param {number} index - The index of the currently rendered item.
  356. * @returns {?React$Element<*>}
  357. */
  358. _renderItem(flatListItem, index) {
  359. const { item } = flatListItem;
  360. const { inviteItems } = this.state;
  361. let selected = false;
  362. let renderableItem;
  363. switch (item.type) {
  364. case 'phone':
  365. selected
  366. = inviteItems.find(_.matchesProperty('number', item.number));
  367. renderableItem = {
  368. avatar: 'phone',
  369. key: item.number,
  370. title: item.number
  371. };
  372. break;
  373. case 'user':
  374. selected
  375. = item.id
  376. ? inviteItems.find(_.matchesProperty('id', item.id))
  377. : inviteItems.find(_.matchesProperty('user_id', item.user_id));
  378. renderableItem = {
  379. avatar: item.avatar,
  380. key: item.id || item.user_id,
  381. title: item.name
  382. };
  383. break;
  384. default:
  385. return null;
  386. }
  387. return (
  388. <TouchableOpacity onPress = { this._onPressItem(item) } >
  389. <View
  390. pointerEvents = 'box-only'
  391. style = { styles.itemWrapper }>
  392. <Icon
  393. name = { selected
  394. ? 'radio_button_checked'
  395. : 'radio_button_unchecked' }
  396. style = { styles.radioButton } />
  397. <AvatarListItem
  398. avatarSize = { AVATAR_SIZE }
  399. avatarStyle = { styles.avatar }
  400. avatarTextStyle = { styles.avatarText }
  401. item = { renderableItem }
  402. key = { index }
  403. linesStyle = { styles.itemLinesStyle }
  404. titleStyle = { styles.itemText } />
  405. </View>
  406. </TouchableOpacity>
  407. );
  408. }
  409. _renderSeparator: () => React$Element<*> | null
  410. /**
  411. * Renders the item separator.
  412. *
  413. * @returns {?React$Element<*>}
  414. */
  415. _renderSeparator() {
  416. return (
  417. <View style = { styles.separator } />
  418. );
  419. }
  420. _setFieldRef: ?TextInput => void
  421. /**
  422. * Sets a reference to the input field for later use.
  423. *
  424. * @param {?TextInput} input - The reference to the input field.
  425. * @returns {void}
  426. */
  427. _setFieldRef(input) {
  428. this.inputFieldRef = input;
  429. }
  430. /**
  431. * Shows an alert telling the user that some invitees were failed to be
  432. * invited.
  433. *
  434. * NOTE: We're using an Alert here because we're on a modal and it makes
  435. * using our dialogs a tad more difficult.
  436. *
  437. * @returns {void}
  438. */
  439. _showFailedInviteAlert() {
  440. const { t } = this.props;
  441. Alert.alert(
  442. t('inviteDialog.alertTitle'),
  443. t('inviteDialog.alertText'),
  444. [
  445. {
  446. text: t('inviteDialog.alertOk')
  447. }
  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));