Delete/resend message (#136)

* Fixed temp message

* Delete/resend working

* Edit message fixed
This commit is contained in:
Diego Mello 2017-12-13 13:00:26 -02:00 committed by Guilherme Gazzo
parent e42a146e4f
commit 7ea98f1337
11 changed files with 198 additions and 36 deletions

View File

@ -34,6 +34,8 @@ export const MESSAGES = createRequestTypes('MESSAGES', [
...defaultTypes, ...defaultTypes,
'ACTIONS_SHOW', 'ACTIONS_SHOW',
'ACTIONS_HIDE', 'ACTIONS_HIDE',
'ERROR_ACTIONS_SHOW',
'ERROR_ACTIONS_HIDE',
'DELETE_REQUEST', 'DELETE_REQUEST',
'DELETE_SUCCESS', 'DELETE_SUCCESS',
'DELETE_FAILURE', 'DELETE_FAILURE',

View File

@ -33,6 +33,19 @@ export function actionsHide() {
}; };
} }
export function errorActionsShow(actionMessage) {
return {
type: types.MESSAGES.ERROR_ACTIONS_SHOW,
actionMessage
};
}
export function errorActionsHide() {
return {
type: types.MESSAGES.ERROR_ACTIONS_HIDE
};
}
export function deleteRequest(message) { export function deleteRequest(message) {
return { return {
type: types.MESSAGES.DELETE_REQUEST, type: types.MESSAGES.DELETE_REQUEST,

View File

@ -0,0 +1,5 @@
export default {
SENT: 0,
TEMP: 1,
ERROR: 2
};

View File

@ -140,7 +140,6 @@ export default class MessageBox extends React.Component {
} }
submit(message) { submit(message) {
this.component.setNativeProps({ text: '' }); this.component.setNativeProps({ text: '' });
this.props.clearInput();
this.setState({ text: '' }); this.setState({ text: '' });
requestAnimationFrame(() => { requestAnimationFrame(() => {
this.props.typing(false); this.props.typing(false);
@ -156,6 +155,7 @@ export default class MessageBox extends React.Component {
// if is submiting a new message // if is submiting a new message
this.props.onSubmit(message); this.props.onSubmit(message);
} }
this.props.clearInput();
}); });
} }

View File

@ -18,7 +18,6 @@ export default StyleSheet.create({
textArea: { textArea: {
flexDirection: 'row', flexDirection: 'row',
alignItems: 'center', alignItems: 'center',
backgroundColor: 'white',
flexGrow: 0 flexGrow: 0
}, },
textBoxInput: { textBoxInput: {

View File

@ -0,0 +1,76 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import ActionSheet from 'react-native-actionsheet';
import { errorActionsHide } from '../actions/messages';
import RocketChat from '../lib/rocketchat';
import realm from '../lib/realm';
@connect(
state => ({
showErrorActions: state.messages.showErrorActions,
actionMessage: state.messages.actionMessage
}),
dispatch => ({
errorActionsHide: () => dispatch(errorActionsHide())
})
)
export default class MessageActions extends React.Component {
static propTypes = {
errorActionsHide: PropTypes.func.isRequired,
showErrorActions: PropTypes.bool.isRequired,
actionMessage: PropTypes.object
};
constructor(props) {
super(props);
this.handleActionPress = this.handleActionPress.bind(this);
this.options = ['Cancel', 'Delete', 'Resend'];
this.CANCEL_INDEX = 0;
this.DELETE_INDEX = 1;
this.RESEND_INDEX = 2;
}
componentWillReceiveProps(nextProps) {
if (nextProps.showErrorActions !== this.props.showErrorActions && nextProps.showErrorActions) {
this.ActionSheet.show();
}
}
handleResend = () => RocketChat.resendMessage(this.props.actionMessage._id);
handleDelete = () => {
realm.write(() => {
const msg = realm.objects('messages').filtered('_id = $0', this.props.actionMessage._id);
realm.delete(msg);
});
}
handleActionPress = (actionIndex) => {
switch (actionIndex) {
case this.RESEND_INDEX:
this.handleResend();
break;
case this.DELETE_INDEX:
this.handleDelete();
break;
default:
break;
}
this.props.errorActionsHide();
}
render() {
return (
<ActionSheet
ref={o => this.ActionSheet = o}
title='Messages actions'
options={this.options}
cancelButtonIndex={this.CANCEL_INDEX}
destructiveButtonIndex={this.DELETE_INDEX}
onPress={this.handleActionPress}
/>
);
}
}

View File

@ -1,10 +1,11 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { View, StyleSheet, TouchableOpacity, Text } from 'react-native'; import { View, StyleSheet, TouchableHighlight, Text, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import Icon from 'react-native-vector-icons/MaterialIcons';
import moment from 'moment'; import moment from 'moment';
import { actionsShow } from '../../actions/messages'; import { actionsShow, errorActionsShow } from '../../actions/messages';
import Image from './Image'; import Image from './Image';
import User from './User'; import User from './User';
import Avatar from '../Avatar'; import Avatar from '../Avatar';
@ -13,6 +14,7 @@ import Video from './Video';
import Markdown from './Markdown'; import Markdown from './Markdown';
import Url from './Url'; import Url from './Url';
import Reply from './Reply'; import Reply from './Reply';
import messageStatus from '../../constants/messagesStatus';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
content: { content: {
@ -39,7 +41,8 @@ const styles = StyleSheet.create({
message: state.messages.message, message: state.messages.message,
editing: state.messages.editing editing: state.messages.editing
}), dispatch => ({ }), dispatch => ({
actionsShow: actionMessage => dispatch(actionsShow(actionMessage)) actionsShow: actionMessage => dispatch(actionsShow(actionMessage)),
errorActionsShow: actionMessage => dispatch(errorActionsShow(actionMessage))
})) }))
export default class Message extends React.Component { export default class Message extends React.Component {
static propTypes = { static propTypes = {
@ -49,7 +52,8 @@ export default class Message extends React.Component {
message: PropTypes.object.isRequired, message: PropTypes.object.isRequired,
user: PropTypes.object.isRequired, user: PropTypes.object.isRequired,
editing: PropTypes.bool, editing: PropTypes.bool,
actionsShow: PropTypes.func actionsShow: PropTypes.func,
errorActionsShow: PropTypes.func
} }
onLongPress() { onLongPress() {
@ -57,6 +61,11 @@ export default class Message extends React.Component {
this.props.actionsShow(JSON.parse(JSON.stringify(item))); this.props.actionsShow(JSON.parse(JSON.stringify(item)));
} }
onErrorPress() {
const { item } = this.props;
this.props.errorActionsShow(JSON.parse(JSON.stringify(item)));
}
isDeleted() { isDeleted() {
return this.props.item.t === 'rm'; return this.props.item.t === 'rm';
} }
@ -65,6 +74,10 @@ export default class Message extends React.Component {
return this.props.item.t === 'message_pinned'; return this.props.item.t === 'message_pinned';
} }
hasError() {
return this.props.item.status === messageStatus.ERROR;
}
attachments() { attachments() {
if (this.props.item.attachments.length === 0) { if (this.props.item.attachments.length === 0) {
return null; return null;
@ -102,13 +115,24 @@ export default class Message extends React.Component {
)); ));
} }
renderError = () => {
if (!this.hasError()) {
return null;
}
return (
<TouchableOpacity onPress={() => this.onErrorPress()}>
<Icon name='error-outline' color='red' size={20} style={{ padding: 10, paddingRight: 12, paddingLeft: 0 }} />
</TouchableOpacity>
);
}
render() { render() {
const { const {
item, message, editing item, message, editing, baseUrl
} = this.props; } = this.props;
const extraStyle = {}; const extraStyle = {};
if (item.temp) { if (item.status === messageStatus.TEMP || item.status === messageStatus.ERROR) {
extraStyle.opacity = 0.3; extraStyle.opacity = 0.3;
} }
@ -118,17 +142,22 @@ export default class Message extends React.Component {
const accessibilityLabel = `Message from ${ item.alias || item.u.username } at ${ moment(item.ts).format(this.props.Message_TimeFormat) }, ${ this.props.item.msg }`; const accessibilityLabel = `Message from ${ item.alias || item.u.username } at ${ moment(item.ts).format(this.props.Message_TimeFormat) }, ${ this.props.item.msg }`;
return ( return (
<TouchableOpacity <TouchableHighlight
onLongPress={() => this.onLongPress()} onLongPress={() => this.onLongPress()}
disabled={this.isDeleted()} disabled={this.isDeleted() || this.hasError()}
style={[styles.message, extraStyle, isEditing ? styles.editing : null]} underlayColor='#FFFFFF'
activeOpacity={0.3}
style={[styles.message, isEditing ? styles.editing : null]}
accessibilityLabel={accessibilityLabel} accessibilityLabel={accessibilityLabel}
> >
<View style={{ flexDirection: 'row', flex: 1 }}>
{this.renderError()}
<View style={[extraStyle, { flexDirection: 'row', flex: 1 }]}>
<Avatar <Avatar
style={{ marginRight: 10 }} style={{ marginRight: 10 }}
text={item.avatar ? '' : username} text={item.avatar ? '' : username}
size={40} size={40}
baseUrl={this.props.baseUrl} baseUrl={baseUrl}
avatar={item.avatar} avatar={item.avatar}
/> />
<View style={[styles.content]}> <View style={[styles.content]}>
@ -136,13 +165,15 @@ export default class Message extends React.Component {
onPress={this._onPress} onPress={this._onPress}
item={item} item={item}
Message_TimeFormat={this.props.Message_TimeFormat} Message_TimeFormat={this.props.Message_TimeFormat}
baseUrl={this.props.baseUrl} baseUrl={baseUrl}
/> />
{this.renderMessageContent()} {this.renderMessageContent()}
{this.attachments()} {this.attachments()}
{this.renderUrl()} {this.renderUrl()}
</View> </View>
</TouchableOpacity> </View>
</View>
</TouchableHighlight>
); );
} }
} }

View File

@ -172,7 +172,7 @@ const messagesSchema = {
attachments: { type: 'list', objectType: 'attachment' }, attachments: { type: 'list', objectType: 'attachment' },
urls: { type: 'list', objectType: 'url' }, urls: { type: 'list', objectType: 'url' },
_updatedAt: { type: 'date', optional: true }, _updatedAt: { type: 'date', optional: true },
temp: { type: 'bool', optional: true }, status: { type: 'int', optional: true },
pinned: { type: 'bool', optional: true }, pinned: { type: 'bool', optional: true },
starred: { type: 'bool', optional: true }, starred: { type: 'bool', optional: true },
editedBy: 'messagesEditedBy' editedBy: 'messagesEditedBy'

View File

@ -6,6 +6,7 @@ import { hashPassword } from 'react-native-meteor/lib/utils';
import RNFetchBlob from 'react-native-fetch-blob'; import RNFetchBlob from 'react-native-fetch-blob';
import reduxStore from './createStore'; import reduxStore from './createStore';
import settingsType from '../constants/settings'; import settingsType from '../constants/settings';
import messagesStatus from '../constants/messagesStatus';
import realm from './realm'; import realm from './realm';
import * as actions from '../actions'; import * as actions from '../actions';
import { someoneTyping } from '../actions/room'; import { someoneTyping } from '../actions/room';
@ -24,6 +25,7 @@ const call = (method, ...params) => new Promise((resolve, reject) => {
}); });
}); });
const TOKEN_KEY = 'reactnativemeteor_usertoken'; const TOKEN_KEY = 'reactnativemeteor_usertoken';
const SERVER_TIMEOUT = 30000;
const RocketChat = { const RocketChat = {
TOKEN_KEY, TOKEN_KEY,
@ -291,7 +293,7 @@ const RocketChat = {
}, },
_buildMessage(message) { _buildMessage(message) {
const { server } = reduxStore.getState().server; const { server } = reduxStore.getState().server;
message.temp = false; message.status = messagesStatus.SENT;
message._server = { id: server }; message._server = { id: server };
message.attachments = message.attachments || []; message.attachments = message.attachments || [];
if (message.urls) { if (message.urls) {
@ -341,7 +343,7 @@ const RocketChat = {
msg, msg,
ts: new Date(), ts: new Date(),
_updatedAt: new Date(), _updatedAt: new Date(),
temp: true, status: messagesStatus.TEMP,
_server: { id: reduxStore.getState().server.server }, _server: { id: reduxStore.getState().server.server },
u: { u: {
_id: reduxStore.getState().login.user.id || '1', _id: reduxStore.getState().login.user.id || '1',
@ -355,9 +357,29 @@ const RocketChat = {
}); });
return message; return message;
}, },
sendMessage(rid, msg) { async _sendMessageCall(message) {
const { _id, rid, msg } = message;
const sendMessageCall = call('sendMessage', { _id, rid, msg });
const timeoutCall = new Promise(resolve => setTimeout(resolve, SERVER_TIMEOUT, 'timeout'));
const result = await Promise.race([sendMessageCall, timeoutCall]);
if (result === 'timeout') {
realm.write(() => {
message.status = messagesStatus.ERROR;
realm.create('messages', message, true);
});
}
},
async sendMessage(rid, msg) {
const tempMessage = this.getMessage(rid, msg); const tempMessage = this.getMessage(rid, msg);
return call('sendMessage', { _id: tempMessage._id, rid, msg }); return RocketChat._sendMessageCall(tempMessage);
},
async resendMessage(messageId) {
const message = await realm.objects('messages').filtered('_id = $0', messageId)[0];
realm.write(() => {
message.status = messagesStatus.TEMP;
realm.create('messages', message, true);
});
return RocketChat._sendMessageCall(message);
}, },
spotlight(search, usernames) { spotlight(search, usernames) {

View File

@ -7,7 +7,8 @@ const initialState = {
actionMessage: {}, actionMessage: {},
editing: false, editing: false,
permalink: '', permalink: '',
showActions: false showActions: false,
showErrorActions: false
}; };
export default function messages(state = initialState, action) { export default function messages(state = initialState, action) {
@ -40,6 +41,17 @@ export default function messages(state = initialState, action) {
...state, ...state,
showActions: false showActions: false
}; };
case types.MESSAGES.ERROR_ACTIONS_SHOW:
return {
...state,
showErrorActions: true,
actionMessage: action.actionMessage
};
case types.MESSAGES.ERROR_ACTIONS_HIDE:
return {
...state,
showErrorActions: false
};
case types.MESSAGES.EDIT_INIT: case types.MESSAGES.EDIT_INIT:
return { return {
...state, ...state,

View File

@ -12,6 +12,7 @@ import realm from '../../lib/realm';
import RocketChat from '../../lib/rocketchat'; import RocketChat from '../../lib/rocketchat';
import Message from '../../containers/message'; import Message from '../../containers/message';
import MessageActions from '../../containers/MessageActions'; import MessageActions from '../../containers/MessageActions';
import MessageErrorActions from '../../containers/MessageErrorActions';
import MessageBox from '../../containers/MessageBox'; import MessageBox from '../../containers/MessageBox';
import Typing from '../../containers/Typing'; import Typing from '../../containers/Typing';
import KeyboardView from '../../presentation/KeyboardView'; import KeyboardView from '../../presentation/KeyboardView';
@ -137,7 +138,7 @@ export default class RoomView extends React.Component {
renderItem = ({ item }) => ( renderItem = ({ item }) => (
<Message <Message
id={item._id} key={item._id}
item={item} item={item}
baseUrl={this.props.Site_Url} baseUrl={this.props.Site_Url}
Message_TimeFormat={this.props.Message_TimeFormat} Message_TimeFormat={this.props.Message_TimeFormat}
@ -187,6 +188,7 @@ export default class RoomView extends React.Component {
</SafeAreaView> </SafeAreaView>
{this.renderFooter()} {this.renderFooter()}
<MessageActions room={this.room} /> <MessageActions room={this.room} />
<MessageErrorActions />
</KeyboardView> </KeyboardView>
); );
} }