verdnatura-chat/app/views/RoomsListView/index.js

309 lines
7.4 KiB
JavaScript
Raw Normal View History

2017-08-03 18:23:43 +00:00
import React from 'react';
2017-08-05 18:16:32 +00:00
import PropTypes from 'prop-types';
import { Platform, View, TextInput, FlatList, BackHandler } from 'react-native';
2017-08-13 01:35:09 +00:00
import { connect } from 'react-redux';
import { iconsMap } from '../../Icons';
import database from '../../lib/realm';
import RocketChat from '../../lib/rocketchat';
import RoomItem from '../../presentation/RoomItem';
import styles from './styles';
import debounce from '../../utils/debounce';
import LoggedView from '../View';
import log from '../../utils/log';
2018-06-01 17:38:13 +00:00
import I18n from '../../i18n';
2017-08-03 18:23:43 +00:00
2017-08-13 01:35:09 +00:00
@connect(state => ({
userId: state.login.user && state.login.user.id,
server: state.server.server,
Site_Url: state.settings.Site_Url,
searchText: state.rooms.searchText
2017-08-13 01:35:09 +00:00
}))
/** @extends React.Component */
export default class RoomsListView extends LoggedView {
2017-08-05 18:16:32 +00:00
static propTypes = {
navigator: PropTypes.object,
userId: PropTypes.string,
Site_Url: PropTypes.string,
server: PropTypes.string,
searchText: PropTypes.string
2017-08-10 14:59:07 +00:00
}
2017-08-09 16:19:17 +00:00
2017-08-03 18:23:43 +00:00
constructor(props) {
super('RoomsListView', props);
2017-08-10 16:16:32 +00:00
this.state = {
search: [],
rooms: []
2017-08-10 16:16:32 +00:00
};
props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
2017-08-21 00:11:46 +00:00
}
async componentWillMount() {
this.initDefaultHeader();
2017-08-13 01:35:09 +00:00
}
componentDidMount() {
this.getSubscriptions();
}
componentWillReceiveProps(props) {
if (this.props.server !== props.server && props.server) {
this.getSubscriptions();
} else if (this.props.searchText !== props.searchText) {
this.search(props.searchText);
}
}
2018-03-02 21:31:44 +00:00
2017-08-09 16:19:17 +00:00
componentWillUnmount() {
2018-03-02 21:31:44 +00:00
this.updateState.stop();
if (this.data) {
this.data.removeAllListeners();
}
}
onNavigatorEvent(event) {
const { navigator } = this.props;
if (event.type === 'NavBarButtonPress') {
if (event.id === 'createChannel') {
navigator.push({
screen: 'SelectedUsersView',
title: I18n.t('Select_Users'),
passProps: {
nextAction: 'CREATE_CHANNEL'
}
});
} else if (event.id === 'sideMenu' && Platform.OS === 'ios') {
navigator.toggleDrawer({
side: 'left',
animated: true,
to: 'missing'
});
} else if (event.id === 'search') {
this.initSearchingAndroid();
} else if (event.id === 'cancelSearch') {
this.cancelSearchingAndroid();
}
} else if (event.type === 'ScreenChangedEvent' && event.id === 'didAppear') {
this.props.navigator.setDrawerEnabled({
side: 'left',
enabled: true
});
}
2017-08-12 20:52:55 +00:00
}
onSearchChangeText(text) {
this.search(text);
}
getSubscriptions = () => {
if (this.data && this.data.removeListener) {
this.data.removeListener(this.updateState);
}
if (this.props.server && this.hasActiveDB()) {
this.data = database.objects('subscriptions').filtered('archived != true && open == true').sorted('roomUpdatedAt', true);
this.data.addListener(this.updateState);
}
}
initDefaultHeader = () => {
const { navigator } = this.props;
const rightButtons = [{
id: 'createChannel',
icon: iconsMap.add,
testID: 'rooms-list-view-create-channel'
}];
if (Platform.OS === 'android') {
rightButtons.push({
id: 'search',
icon: iconsMap.search
});
}
navigator.setButtons({
leftButtons: [{
id: 'sideMenu',
icon: Platform.OS === 'ios' ? iconsMap.menu : undefined,
testID: 'rooms-list-view-sidebar'
}],
rightButtons
});
}
initSearchingAndroid = () => {
const { navigator } = this.props;
navigator.setButtons({
leftButtons: [{
id: 'cancelSearch',
icon: iconsMap['md-arrow-back']
}],
rightButtons: []
});
navigator.setStyle({
navBarCustomView: 'RoomsListSearchView',
navBarComponentAlignment: 'fill'
});
BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
}
// this is necessary during development (enables Cmd + r)
hasActiveDB = () => database && database.databases && database.databases.activeDB;
cancelSearchingAndroid = () => {
if (Platform.OS === 'android') {
this.props.navigator.setStyle({
navBarCustomView: ''
});
this.setState({ search: [] });
this.initDefaultHeader();
BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
}
}
handleBackPress = () => {
this.cancelSearchingAndroid();
return true;
}
updateState = debounce(() => {
this.setState({ rooms: this.data.slice() });
})
2018-03-02 21:31:44 +00:00
async search(text) {
2017-08-10 16:16:32 +00:00
const searchText = text.trim();
if (searchText === '') {
2018-03-02 21:31:44 +00:00
delete this.oldPromise;
return this.setState({
Beta (#265) * Fabric iOS * Fabric configured on iOS and Android * - react-native-fabric configured - login tracked * README updated * Run scripts from README updated * README scripts * get rooms and messages by rest * user status * more improves * more improves * send pong on timeout * fix some methods * more tests * rest messages * Room actions (#266) * Toggle notifications * Search messages * Invite users * Mute/Unmute users in room * rocket.cat messages * Room topic layout fixed * Starred messages loading onEndReached * Room actions onEndReached * Unnecessary login request * Login loading * Login services fixed * User presence layout * ïmproves on room actions view * Removed unnecessary data from SelectedUsersView * load few messages on open room, search message improve * fix loading messages forever * Removed state from search * Custom message time format * secureTextEntry layout * Reduce android app size * Roles subscription fix * Public routes navigation * fix reconnect * - New login/register, login, register * proguard * Login flux * App init/restore * Android layout fixes * Multiple meteor connection requests fixed * Nested attachments * Nested attachments * fix check status * New login layout (#269) * Public routes navigation * New login/register, login, register * Multiple meteor connection requests fixed * Nested attachments * Button component * TextInput android layout fixed * Register fixed * Thinner close modal button * Requests /me after login only one time * Static images moved * fix reconnect * fix ddp * fix custom emoji * New message layout (#273) * Grouping messages * Message layout * Users typing animation * Image attachment layout
2018-04-24 19:34:03 +00:00
search: []
});
}
2017-08-09 18:01:54 +00:00
let data = database.objects('subscriptions').filtered('name CONTAINS[c] $0', searchText).slice(0, 7);
2018-03-02 21:31:44 +00:00
const usernames = data.map(sub => sub.name);
2018-03-02 21:31:44 +00:00
try {
if (data.length < 7) {
if (this.oldPromise) {
this.oldPromise('cancel');
}
const { users, rooms } = await Promise.race([
RocketChat.spotlight(searchText, usernames, { users: true, rooms: true }),
new Promise((resolve, reject) => this.oldPromise = reject)
]);
data = data.concat(users.map(user => ({
...user,
rid: user.username,
name: user.username,
t: 'd',
search: true
})), rooms.map(room => ({
rid: room._id,
...room,
search: true
})));
delete this.oldPromise;
}
2017-08-10 16:16:32 +00:00
this.setState({
2018-03-02 21:31:44 +00:00
search: data
2017-08-10 16:16:32 +00:00
});
2018-03-02 21:31:44 +00:00
} catch (e) {
// alert(JSON.stringify(e));
}
}
2017-08-10 16:16:32 +00:00
goRoom = (rid, name) => {
this.props.navigator.push({
screen: 'RoomView',
title: name,
passProps: {
room: { rid, name },
rid,
name
}
});
this.cancelSearchingAndroid();
}
2018-03-02 21:31:44 +00:00
_onPressItem = async(item = {}) => {
if (!item.search) {
const { rid, name } = item;
return this.goRoom(rid, name);
2017-08-10 16:16:32 +00:00
}
2018-03-02 21:31:44 +00:00
if (item.t === 'd') {
// if user is using the search we need first to join/create room
try {
const { username } = item;
const sub = await RocketChat.createDirectMessage(username);
const { rid } = sub;
return this.goRoom(rid, username);
} catch (e) {
log('RoomsListView._onPressItem', e);
}
} else {
const { rid, name } = item;
return this.goRoom(rid, name);
2018-03-02 21:31:44 +00:00
}
2017-08-05 18:16:32 +00:00
}
2017-08-10 16:16:32 +00:00
renderSearchBar = () => (
<View style={styles.searchBoxView}>
<TextInput
underlineColorAndroid='transparent'
style={styles.searchBox}
onChangeText={text => this.onSearchChangeText(text)}
returnKeyType='search'
2018-06-01 17:38:13 +00:00
placeholder={I18n.t('Search')}
2017-08-10 20:31:14 +00:00
clearButtonMode='while-editing'
blurOnSubmit
autoCorrect={false}
autoCapitalize='none'
2018-05-23 13:39:18 +00:00
testID='rooms-list-view-search'
/>
</View>
2017-08-10 16:16:32 +00:00
);
renderItem = ({ item }) => {
const id = item.rid.replace(this.props.userId, '').trim();
return (<RoomItem
alert={item.alert}
unread={item.unread}
userMentions={item.userMentions}
favorite={item.f}
lastMessage={item.lastMessage}
2017-08-21 16:16:23 +00:00
name={item.name}
_updatedAt={item.roomUpdatedAt}
key={item._id}
id={id}
2017-08-21 16:16:23 +00:00
type={item.t}
2017-08-21 00:11:46 +00:00
baseUrl={this.props.Site_Url}
onPress={() => this._onPressItem(item)}
2018-05-23 13:39:18 +00:00
testID={`rooms-list-view-item-${ item.name }`}
/>);
}
2017-08-11 18:18:09 +00:00
renderList = () => (
<FlatList
data={this.state.search.length > 0 ? this.state.search : this.state.rooms}
extraData={this.state.search.length > 0 ? this.state.search : this.state.rooms}
keyExtractor={item => item.rid}
2017-08-11 18:18:09 +00:00
style={styles.list}
renderItem={this.renderItem}
ListHeaderComponent={Platform.OS === 'ios' ? this.renderSearchBar : null}
contentOffset={Platform.OS === 'ios' ? { x: 0, y: 38 } : {}}
2017-08-12 20:52:55 +00:00
enableEmptySections
Beta (#265) * Fabric iOS * Fabric configured on iOS and Android * - react-native-fabric configured - login tracked * README updated * Run scripts from README updated * README scripts * get rooms and messages by rest * user status * more improves * more improves * send pong on timeout * fix some methods * more tests * rest messages * Room actions (#266) * Toggle notifications * Search messages * Invite users * Mute/Unmute users in room * rocket.cat messages * Room topic layout fixed * Starred messages loading onEndReached * Room actions onEndReached * Unnecessary login request * Login loading * Login services fixed * User presence layout * ïmproves on room actions view * Removed unnecessary data from SelectedUsersView * load few messages on open room, search message improve * fix loading messages forever * Removed state from search * Custom message time format * secureTextEntry layout * Reduce android app size * Roles subscription fix * Public routes navigation * fix reconnect * - New login/register, login, register * proguard * Login flux * App init/restore * Android layout fixes * Multiple meteor connection requests fixed * Nested attachments * Nested attachments * fix check status * New login layout (#269) * Public routes navigation * New login/register, login, register * Multiple meteor connection requests fixed * Nested attachments * Button component * TextInput android layout fixed * Register fixed * Thinner close modal button * Requests /me after login only one time * Static images moved * fix reconnect * fix ddp * fix custom emoji * New message layout (#273) * Grouping messages * Message layout * Users typing animation * Image attachment layout
2018-04-24 19:34:03 +00:00
removeClippedSubviews
2017-08-14 18:02:53 +00:00
keyboardShouldPersistTaps='always'
2018-05-23 13:39:18 +00:00
testID='rooms-list-view-list'
2017-08-11 18:18:09 +00:00
/>
)
render = () => (
2018-05-23 13:39:18 +00:00
<View style={styles.container} testID='rooms-list-view'>
{this.renderList()}
2017-08-21 00:11:46 +00:00
</View>)
2017-08-03 18:23:43 +00:00
}