Rocket.Chat.ReactNative/app/views/RoomsListView/index.js

573 lines
16 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, ActivityIndicator, SafeAreaView, Text, Image, Dimensions, ScrollView, Keyboard } from 'react-native';
2017-08-13 01:35:09 +00:00
import { connect } from 'react-redux';
import { isEqual } from 'lodash';
import database from '../../lib/realm';
import RocketChat from '../../lib/rocketchat';
import RoomItem from '../../presentation/RoomItem';
import styles from './styles';
import LoggedView from '../View';
import log from '../../utils/log';
2018-06-01 17:38:13 +00:00
import I18n from '../../i18n';
import SortDropdown from './SortDropdown';
import ServerDropdown from './ServerDropdown';
import Touch from '../../utils/touch';
import { toggleSortDropdown } from '../../actions/rooms';
const ROW_HEIGHT = 70;
const isAndroid = () => Platform.OS === 'android';
const getItemLayout = (data, index) => ({ length: ROW_HEIGHT, offset: ROW_HEIGHT * index, index });
const leftButtons = [{
id: 'settings',
icon: { uri: 'settings', scale: Dimensions.get('window').scale },
testID: 'rooms-list-view-sidebar'
}];
const rightButtons = [{
id: 'createChannel',
icon: { uri: 'new_channel', scale: Dimensions.get('window').scale },
testID: 'rooms-list-view-create-channel'
}];
if (Platform.OS === 'android') {
rightButtons.push({
id: 'search',
icon: { uri: 'search', scale: Dimensions.get('window').scale }
});
}
2017-08-03 18:23:43 +00:00
@connect((state) => {
let result = {
userId: state.login.user && state.login.user.id,
server: state.server.server,
Site_Url: state.settings.Site_Url,
searchText: state.rooms.searchText,
loadingServer: state.server.loading,
showServerDropdown: state.rooms.showServerDropdown,
showSortDropdown: state.rooms.showSortDropdown,
sidebarSortby: null,
sidebarGroupByType: null,
sidebarShowFavorites: null,
sidebarShowUnread: null
};
if (state.login && state.login.user && state.login.user.settings && state.login.user.settings.preferences) {
result = {
...result,
sidebarSortby: state.login.user.settings.preferences.sidebarSortby,
sidebarGroupByType: state.login.user.settings.preferences.sidebarGroupByType,
sidebarShowFavorites: state.login.user.settings.preferences.sidebarShowFavorites,
sidebarShowUnread: state.login.user.settings.preferences.sidebarShowUnread
};
}
return result;
}, dispatch => ({
toggleSortDropdown: () => dispatch(toggleSortDropdown())
2017-08-13 01:35:09 +00:00
}))
/** @extends React.Component */
export default class RoomsListView extends LoggedView {
static navigatorButtons = {
leftButtons, rightButtons
}
static navigatorStyle = {
navBarCustomView: 'RoomsListHeaderView',
navBarComponentAlignment: 'fill',
navBarBackgroundColor: isAndroid() ? '#2F343D' : undefined,
navBarTextColor: isAndroid() ? '#FFF' : undefined,
navBarButtonColor: isAndroid() ? '#FFF' : undefined
}
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,
loadingServer: PropTypes.bool,
showServerDropdown: PropTypes.bool,
showSortDropdown: PropTypes.bool,
sidebarSortby: PropTypes.string,
sidebarGroupByType: PropTypes.bool,
sidebarShowFavorites: PropTypes.bool,
sidebarShowUnread: PropTypes.bool,
toggleSortDropdown: PropTypes.func
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: [],
loading: true,
chats: [],
unread: [],
favorites: [],
channels: [],
privateGroup: [],
direct: [],
livechat: []
2017-08-10 16:16:32 +00:00
};
props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
2017-08-21 00:11:46 +00:00
}
componentWillMount() {
this.initDefaultHeader();
2017-08-13 01:35:09 +00:00
}
componentDidMount() {
this.getSubscriptions();
}
componentWillReceiveProps(nextProps) {
if (nextProps.server && this.props.loadingServer !== nextProps.loadingServer) {
if (nextProps.loadingServer) {
this.setState({ loading: true });
} else {
this.getSubscriptions();
}
} else if (this.props.searchText !== nextProps.searchText) {
this.search(nextProps.searchText);
}
}
shouldComponentUpdate(nextProps, nextState) {
return !(isEqual(this.props, nextProps) && isEqual(this.state, nextState));
}
componentDidUpdate(prevProps) {
if (!(
(prevProps.sidebarSortby === this.props.sidebarSortby) &&
(prevProps.sidebarGroupByType === this.props.sidebarGroupByType) &&
(prevProps.sidebarShowFavorites === this.props.sidebarShowFavorites) &&
(prevProps.sidebarShowUnread === this.props.sidebarShowUnread)
)) {
this.getSubscriptions();
}
}
2018-03-02 21:31:44 +00:00
2017-08-09 16:19:17 +00:00
componentWillUnmount() {
this.removeListener(this.data);
this.removeListener(this.unread);
this.removeListener(this.favorites);
this.removeListener(this.channels);
this.removeListener(this.privateGroup);
this.removeListener(this.direct);
this.removeListener(this.livechat);
if (this.timeout) {
clearTimeout(this.timeout);
}
}
onNavigatorEvent(event) {
const { navigator } = this.props;
if (event.type === 'NavBarButtonPress') {
if (event.id === 'createChannel') {
this.props.navigator.push({
screen: 'SelectedUsersView',
title: I18n.t('Select_Users'),
passProps: {
nextAction: 'CREATE_CHANNEL'
}
});
} else if (event.id === 'settings') {
navigator.toggleDrawer({
side: 'left'
});
} else if (event.id === 'search') {
this.initSearchingAndroid();
} else if (event.id === 'cancelSearch' || event.id === 'back') {
this.cancelSearchingAndroid();
}
} else if (event.type === 'ScreenChangedEvent' && event.id === 'didAppear') {
navigator.setDrawerEnabled({
side: 'left',
enabled: true
});
}
2017-08-12 20:52:55 +00:00
}
onSearchChangeText(text) {
this.search(text);
}
getSubscriptions = () => {
if (this.props.server && this.hasActiveDB()) {
if (this.props.sidebarSortby === 'alphabetical') {
this.data = database.objects('subscriptions').filtered('archived != true && open == true').sorted('name', false);
} else {
this.data = database.objects('subscriptions').filtered('archived != true && open == true').sorted('roomUpdatedAt', true);
}
let chats = [];
let unread = [];
let favorites = [];
let channels = [];
let privateGroup = [];
let direct = [];
let livechat = [];
// unread
if (this.props.sidebarShowUnread) {
this.unread = this.data.filtered('archived != true && open == true').sorted('name', false).filtered('(unread > 0 || alert == true)');
unread = this.unread.slice();
setTimeout(() => {
this.unread.addListener(() => this.setState({ unread: this.unread.slice() }));
});
} else {
this.removeListener(unread);
}
// favorites
if (this.props.sidebarShowFavorites) {
this.favorites = this.data.filtered('f == true');
favorites = this.favorites.slice();
setTimeout(() => {
this.favorites.addListener(() => this.setState({ favorites: this.favorites.slice() }));
});
} else {
this.removeListener(favorites);
}
// type
if (this.props.sidebarGroupByType) {
// channels
this.channels = this.data.filtered('t == $0', 'c');
channels = this.channels.slice();
// private
this.privateGroup = this.data.filtered('t == $0', 'p');
privateGroup = this.privateGroup.slice();
// direct
this.direct = this.data.filtered('t == $0', 'd');
direct = this.direct.slice();
// livechat
this.livechat = this.data.filtered('t == $0', 'l');
livechat = this.livechat.slice();
setTimeout(() => {
this.channels.addListener(() => this.setState({ channels: this.channels.slice() }));
this.privateGroup.addListener(() => this.setState({ privateGroup: this.privateGroup.slice() }));
this.direct.addListener(() => this.setState({ direct: this.direct.slice() }));
this.livechat.addListener(() => this.setState({ livechat: this.livechat.slice() }));
});
this.removeListener(this.chats);
} else {
// chats
this.chats = this.data.filtered('(unread == 0 && alert == false)');
chats = this.chats.slice();
setTimeout(() => {
this.chats.addListener(() => this.setState({ chats: this.chats.slice() }));
});
this.removeListener(this.channels);
this.removeListener(this.privateGroup);
this.removeListener(this.direct);
this.removeListener(this.livechat);
}
// setState
this.setState({
chats, unread, favorites, channels, privateGroup, direct, livechat
});
}
this.timeout = setTimeout(() => {
this.setState({ loading: false });
}, 200);
}
removeListener = (data) => {
if (data && data.removeAllListeners) {
data.removeAllListeners();
}
}
initDefaultHeader = () => {
const { navigator } = this.props;
navigator.setButtons({ leftButtons, rightButtons });
navigator.setStyle({
navBarCustomView: 'RoomsListHeaderView',
navBarComponentAlignment: 'fill',
navBarBackgroundColor: isAndroid() ? '#2F343D' : undefined,
navBarTextColor: isAndroid() ? '#FFF' : undefined,
navBarButtonColor: isAndroid() ? '#FFF' : undefined
});
}
initSearchingAndroid = () => {
const { navigator } = this.props;
navigator.setButtons({
leftButtons: [{
id: 'cancelSearch',
icon: { uri: 'back', scale: Dimensions.get('window').scale }
}],
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.setState({ search: [] });
this.initDefaultHeader();
Keyboard.dismiss();
BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
}
}
handleBackPress = () => {
this.cancelSearchingAndroid();
return true;
}
_isUnread = item => item.unread > 0 || item.alert
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
}
toggleSort = () => this.props.toggleSortDropdown();
renderHeader = () => {
if (this.state.search.length > 0) {
return null;
}
return this.renderSort();
}
renderSort = () => (
<Touch
onPress={this.toggleSort}
style={styles.dropdownContainerHeader}
>
<View style={styles.sortItemContainer}>
<Text style={styles.sortToggleText}>{I18n.t('Sorting_by', { key: I18n.t(this.props.sidebarSortby === 'alphabetical' ? 'name' : 'activity') })}</Text>
<Image style={styles.sortIcon} source={{ uri: 'group_type' }} />
</View>
</Touch>
)
renderSearchBar = () => {
if (Platform.OS === 'ios') {
return (
<View style={styles.searchBoxView}>
<TextInput
underlineColorAndroid='transparent'
style={styles.searchBox}
onChangeText={text => this.onSearchChangeText(text)}
returnKeyType='search'
placeholder={I18n.t('Search')}
clearButtonMode='while-editing'
blurOnSubmit
autoCorrect={false}
autoCapitalize='none'
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 }`}
height={ROW_HEIGHT}
/>);
}
renderSeparator = () => <View style={styles.separator} />;
renderSection = (data, header) => {
if (data.length > 0) {
return (
<FlatList
data={data}
extraData={data}
keyExtractor={item => item.rid}
style={styles.list}
renderItem={this.renderItem}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={() => (
<View style={styles.groupTitleContainer}>
<Text style={styles.groupTitle}>{I18n.t(header)}</Text>
</View>
)}
getItemLayout={getItemLayout}
enableEmptySections
removeClippedSubviews
keyboardShouldPersistTaps='always'
/>
);
}
return null;
}
renderList = () => {
const {
search, chats, unread, favorites, channels, direct, privateGroup, livechat
} = this.state;
if (search.length > 0) {
return (
<FlatList
data={search}
extraData={search}
keyExtractor={item => item.rid}
style={styles.list}
renderItem={this.renderItem}
ItemSeparatorComponent={this.renderSeparator}
getItemLayout={getItemLayout}
enableEmptySections
removeClippedSubviews
keyboardShouldPersistTaps='always'
/>
);
}
return (
<View style={styles.container}>
{this.renderSection(unread, 'Unread')}
{this.renderSection(favorites, 'Favorites')}
{this.renderSection(channels, 'Channels')}
{this.renderSection(direct, 'Direct_Messages')}
{this.renderSection(privateGroup, 'Private_Groups')}
{this.renderSection(livechat, 'Livechat')}
{this.renderSection(chats, 'Chats')}
</View>
);
}
renderScroll = () => {
if (this.state.loading) {
return <ActivityIndicator style={styles.loading} />;
}
return (
<ScrollView
contentOffset={Platform.OS === 'ios' ? { x: 0, y: 37 } : {}}
keyboardShouldPersistTaps='always'
testID='rooms-list-view-list'
>
{this.renderSearchBar()}
{this.renderHeader()}
{this.renderList()}
</ScrollView>
);
}
render = () => {
const {
sidebarSortby, sidebarGroupByType, sidebarShowFavorites, sidebarShowUnread, showServerDropdown, showSortDropdown
} = this.props;
return (
<SafeAreaView style={styles.container} testID='rooms-list-view'>
{this.renderScroll()}
{showSortDropdown ?
<SortDropdown
close={this.toggleSort}
sidebarSortby={sidebarSortby}
sidebarGroupByType={sidebarGroupByType}
sidebarShowFavorites={sidebarShowFavorites}
sidebarShowUnread={sidebarShowUnread}
/> :
null}
{showServerDropdown ? <ServerDropdown navigator={this.props.navigator} /> : null}
</SafeAreaView>
);
}
2017-08-03 18:23:43 +00:00
}