diff options
Diffstat (limited to 'web/react/components')
-rw-r--r-- | web/react/components/create_comment.jsx | 217 | ||||
-rw-r--r-- | web/react/components/create_post.jsx | 246 | ||||
-rw-r--r-- | web/react/components/file_preview.jsx | 14 | ||||
-rw-r--r-- | web/react/components/file_upload.jsx | 163 | ||||
-rw-r--r-- | web/react/components/invite_member_modal.jsx | 2 | ||||
-rw-r--r-- | web/react/components/mention_list.jsx | 17 | ||||
-rw-r--r-- | web/react/components/post_list.jsx | 4 | ||||
-rw-r--r-- | web/react/components/settings_sidebar.jsx | 3 | ||||
-rw-r--r-- | web/react/components/sidebar.jsx | 217 | ||||
-rw-r--r-- | web/react/components/sidebar_header.jsx | 2 | ||||
-rw-r--r-- | web/react/components/textbox.jsx | 161 | ||||
-rw-r--r-- | web/react/components/view_image.jsx | 223 |
12 files changed, 685 insertions, 584 deletions
diff --git a/web/react/components/create_comment.jsx b/web/react/components/create_comment.jsx index 88c01c586..78e06c532 100644 --- a/web/react/components/create_comment.jsx +++ b/web/react/components/create_comment.jsx @@ -18,20 +18,24 @@ module.exports = React.createClass({ handleSubmit: function(e) { e.preventDefault(); - if (this.state.uploadsInProgress > 0) return; + if (this.state.uploadsInProgress.length > 0) { + return; + } - if (this.state.submitting) return; + if (this.state.submitting) { + return; + } - var post = {} + var post = {}; post.filenames = []; - post.message = this.state.messageText; + if (post.message.trim().length === 0 && this.state.previews.length === 0) { return; } if (post.message.length > Constants.CHARACTER_LIMIT) { - this.setState({ post_error: 'Comment length must be less than '+Constants.CHARACTER_LIMIT+' characters.' }); + this.setState({postError: 'Comment length must be less than ' + Constants.CHARACTER_LIMIT + ' characters.'}); return; } @@ -40,163 +44,154 @@ module.exports = React.createClass({ post.parent_id = this.props.parentId; post.filenames = this.state.previews; - this.setState({ submitting: true, limit_error: null }); + this.setState({submitting: true, serverError: null}); client.createPost(post, ChannelStore.getCurrent(), function(data) { PostStore.storeCommentDraft(this.props.rootId, null); - this.setState({ messageText: '', submitting: false, post_error: null, server_error: null }); + this.setState({messageText: '', submitting: false, postError: null, serverError: null}); this.clearPreviews(); AsyncClient.getPosts(true, this.props.channelId); var channel = ChannelStore.get(this.props.channelId); var member = ChannelStore.getMember(this.props.channelId); member.msg_count = channel.total_msg_count; - member.last_viewed_at = (new Date).getTime(); + member.last_viewed_at = Date.now(); ChannelStore.setChannelMember(member); - }.bind(this), function(err) { var state = {}; - state.server_error = err.message; + state.serverError = err.message; state.submitting = false; - if (err.message === "Invalid RootId parameter") { - if ($('#post_deleted').length > 0) $('#post_deleted').modal('show'); - } - else { + if (err.message === 'Invalid RootId parameter') { + if ($('#post_deleted').length > 0) { + $('#post_deleted').modal('show'); + } + } else { this.setState(state); } }.bind(this) ); }, commentMsgKeyPress: function(e) { - if (e.which == 13 && !e.shiftKey && !e.altKey) { + if (e.which === 13 && !e.shiftKey && !e.altKey) { e.preventDefault(); this.refs.textbox.getDOMNode().blur(); this.handleSubmit(e); } - var t = new Date().getTime(); + var t = Date.now(); if ((t - this.lastTime) > 5000) { - SocketStore.sendMessage({channel_id: this.props.channelId, action: "typing", props: {"parent_id": this.props.rootId} }); + SocketStore.sendMessage({channel_id: this.props.channelId, action: 'typing', props: {'parent_id': this.props.rootId}}); this.lastTime = t; } }, handleUserInput: function(messageText) { var draft = PostStore.getCommentDraft(this.props.rootId); - if (!draft) { - draft = { previews: [], uploadsInProgress: 0}; - } draft.message = messageText; PostStore.storeCommentDraft(this.props.rootId, draft); - $(".post-right__scroll").scrollTop($(".post-right__scroll")[0].scrollHeight); - $(".post-right__scroll").perfectScrollbar('update'); + $('.post-right__scroll').scrollTop($('.post-right__scroll')[0].scrollHeight); + $('.post-right__scroll').perfectScrollbar('update'); this.setState({messageText: messageText}); }, - handleFileUpload: function(newPreviews) { + handleUploadStart: function(clientIds, channelId) { var draft = PostStore.getCommentDraft(this.props.rootId); - if (!draft) { - draft = { message: '', uploadsInProgress: 0, previews: []} - } - $(".post-right__scroll").scrollTop($(".post-right__scroll")[0].scrollHeight); - $(".post-right__scroll").perfectScrollbar('update'); - var previews = this.state.previews.concat(newPreviews); - var num = this.state.uploadsInProgress; + draft['uploadsInProgress'] = draft['uploadsInProgress'].concat(clientIds); + PostStore.storeCommentDraft(this.props.rootId, draft); - draft.previews = previews; - draft.uploadsInProgress = num-1; + this.setState({uploadsInProgress: draft['uploadsInProgress']}); + }, + handleFileUploadComplete: function(filenames, clientIds, channelId) { + var draft = PostStore.getCommentDraft(this.props.rootId); + + // remove each finished file from uploads + for (var i = 0; i < clientIds.length; i++) { + var index = draft['uploadsInProgress'].indexOf(clientIds[i]); + + if (index !== -1) { + draft['uploadsInProgress'].splice(index, 1); + } + } + + draft['previews'] = draft['previews'].concat(filenames); PostStore.storeCommentDraft(this.props.rootId, draft); - this.setState({previews: previews, uploadsInProgress: num-1}); + this.setState({uploadsInProgress: draft['uploadsInProgress'], previews: draft['previews']}); }, - handleUploadError: function(err) { - this.setState({ server_error: err }); + handleUploadError: function(err, clientId) { + var draft = PostStore.getCommentDraft(this.props.rootId); + + var index = draft['uploadsInProgress'].indexOf(clientId); + if (index !== -1) { + draft['uploadsInProgress'].splice(index, 1); + } + + PostStore.storeCommentDraft(this.props.rootId, draft); + + this.setState({uploadsInProgress: draft['uploadsInProgress'], serverError: err}); }, clearPreviews: function() { this.setState({previews: []}); }, - removePreview: function(filename) { + removePreview: function(id) { var previews = this.state.previews; - for (var i = 0; i < previews.length; i++) { - if (previews[i] === filename) { - previews.splice(i, 1); - break; + var uploadsInProgress = this.state.uploadsInProgress; + + // id can either be the path of an uploaded file or the client id of an in progress upload + var index = previews.indexOf(id); + if (index !== -1) { + previews.splice(index, 1); + } else { + index = uploadsInProgress.indexOf(id); + + if (index !== -1) { + uploadsInProgress.splice(index, 1); + this.refs.fileUpload.cancelUpload(id); } } - var draft = PostStore.getCommentDraft(); - if (!draft) { - draft = { message: '', uploadsInProgress: 0}; - } + var draft = PostStore.getCommentDraft(this.props.rootId); draft.previews = previews; - PostStore.storeCommentDraft(draft); + draft.uploadsInProgress = uploadsInProgress; + PostStore.storeCommentDraft(this.props.rootId, draft); - this.setState({previews: previews}); + this.setState({previews: previews, uploadsInProgress: uploadsInProgress}); }, getInitialState: function() { PostStore.clearCommentDraftUploads(); var draft = PostStore.getCommentDraft(this.props.rootId); - messageText = ''; - uploadsInProgress = 0; - previews = []; - if (draft) { - messageText = draft.message; - uploadsInProgress = draft.uploadsInProgress; - previews = draft.previews - } - return { messageText: messageText, uploadsInProgress: uploadsInProgress, previews: previews, submitting: false }; + return {messageText: draft['message'], uploadsInProgress: draft['uploadsInProgress'], previews: draft['previews'], submitting: false}; }, componentWillReceiveProps: function(newProps) { - if(newProps.rootId !== this.props.rootId) { + if (newProps.rootId !== this.props.rootId) { var draft = PostStore.getCommentDraft(newProps.rootId); - messageText = ''; - uploadsInProgress = 0; - previews = []; - if (draft) { - messageText = draft.message; - uploadsInProgress = draft.uploadsInProgress; - previews = draft.previews - } - this.setState({ messageText: messageText, uploadsInProgress: uploadsInProgress, previews: previews }); + this.setState({messageText: draft['message'], uploadsInProgress: draft['uploadsInProgress'], previews: draft['previews']}); } }, - setUploads: function(val) { - var oldInProgress = this.state.uploadsInProgress - var newInProgress = oldInProgress + val; - - if (newInProgress + this.state.previews.length > Constants.MAX_UPLOAD_FILES) { - newInProgress = Constants.MAX_UPLOAD_FILES - this.state.previews.length; - this.setState({limit_error: "Uploads limited to " + Constants.MAX_UPLOAD_FILES + " files maximum. Please use additional comments for more files."}); - } else { - this.setState({limit_error: null}); - } - - var numToUpload = newInProgress - oldInProgress; - if (numToUpload <= 0) return 0; - - var draft = PostStore.getCommentDraft(this.props.rootId); - if (!draft) { - draft = { message: '', previews: []}; - } - draft.uploadsInProgress = newInProgress; - PostStore.storeCommentDraft(this.props.rootId, draft); - - this.setState({uploadsInProgress: newInProgress}); - - return numToUpload; + getFileCount: function(channelId) { + return this.state.previews.length + this.state.uploadsInProgress.length; }, render: function() { + var serverError = null; + if (this.state.serverError) { + serverError = ( + <div className='form-group has-error'> + <label className='control-label'>{this.state.serverError}</label> + </div> + ); + } - var server_error = this.state.server_error ? <div className='form-group has-error'><label className='control-label'>{ this.state.server_error }</label></div> : null; - var post_error = this.state.post_error ? <label className='control-label'>{this.state.post_error}</label> : null; - var limit_error = this.state.limit_error ? <div className='has-error'><label className='control-label'>{this.state.limit_error}</label></div> : null; + var postError = null; + if (this.state.postError) { + postError = <label className='control-label'>{this.state.postError}</label>; + } - var preview = <div/>; - if (this.state.previews.length > 0 || this.state.uploadsInProgress > 0) { + var preview = null; + if (this.state.previews.length > 0 || this.state.uploadsInProgress.length > 0) { preview = ( <FilePreview files={this.state.previews} @@ -205,32 +200,38 @@ module.exports = React.createClass({ ); } + var postFooterClassName = 'post-create-footer'; + if (postError) { + postFooterClassName += ' has-error'; + } + return ( <form onSubmit={this.handleSubmit}> - <div className="post-create"> - <div id={this.props.rootId} className="post-create-body comment-create-body"> + <div className='post-create'> + <div id={this.props.rootId} className='post-create-body comment-create-body'> <Textbox onUserInput={this.handleUserInput} onKeyPress={this.commentMsgKeyPress} messageText={this.state.messageText} - createMessage="Add a comment..." - initialText="" - id="reply_textbox" - ref="textbox" /> + createMessage='Add a comment...' + initialText='' + id='reply_textbox' + ref='textbox' /> <FileUpload - setUploads={this.setUploads} - onFileUpload={this.handleFileUpload} + ref='fileUpload' + getFileCount={this.getFileCount} + onUploadStart={this.handleUploadStart} + onFileUpload={this.handleFileUploadComplete} onUploadError={this.handleUploadError} /> </div> <MsgTyping channelId={this.props.channelId} parentId={this.props.rootId} /> - <div className={post_error ? 'has-error' : 'post-create-footer'}> - <input type="button" className="btn btn-primary comment-btn pull-right" value="Add Comment" onClick={this.handleSubmit} /> - { post_error } - { server_error } - { limit_error } + <div className={postFooterClassName}> + <input type='button' className='btn btn-primary comment-btn pull-right' value='Add Comment' onClick={this.handleSubmit} /> + {postError} + {serverError} </div> </div> - { preview } + {preview} </form> ); } diff --git a/web/react/components/create_post.jsx b/web/react/components/create_post.jsx index 76286eb88..9ca1d5388 100644 --- a/web/react/components/create_post.jsx +++ b/web/react/components/create_post.jsx @@ -22,13 +22,12 @@ module.exports = React.createClass({ handleSubmit: function(e) { e.preventDefault(); - if (this.state.uploadsInProgress > 0) return; - - if (this.state.submitting) return; + if (this.state.uploadsInProgress.length > 0 || this.state.submitting) { + return; + } var post = {}; post.filenames = []; - post.message = this.state.messageText; if (post.message.trim().length === 0 && this.state.previews.length === 0) { @@ -36,55 +35,52 @@ module.exports = React.createClass({ } if (post.message.length > Constants.CHARACTER_LIMIT) { - this.setState({ post_error: 'Post length must be less than '+Constants.CHARACTER_LIMIT+' characters.' }); + this.setState({postError: 'Post length must be less than ' + Constants.CHARACTER_LIMIT + ' characters.'}); return; } - this.setState({ submitting: true, limit_error: null }); - - var user_id = UserStore.getCurrentId(); + this.setState({submitting: true, serverError: null}); - if (post.message.indexOf("/") == 0) { + if (post.message.indexOf('/') === 0) { client.executeCommand( - this.state.channel_id, + this.state.channelId, post.message, false, function(data) { PostStore.storeDraft(data.channel_id, null); - this.setState({ messageText: '', submitting: false, post_error: null, previews: [], server_error: null, limit_error: null }); + this.setState({messageText: '', submitting: false, postError: null, previews: [], serverError: null}); if (data.goto_location.length > 0) { window.location.href = data.goto_location; } }.bind(this), - function(err){ - var state = {} - state.server_error = err.message; + function(err) { + var state = {}; + state.serverError = err.message; state.submitting = false; this.setState(state); }.bind(this) ); } else { - post.channel_id = this.state.channel_id; + post.channel_id = this.state.channelId; post.filenames = this.state.previews; client.createPost(post, ChannelStore.getCurrent(), function(data) { PostStore.storeDraft(data.channel_id, null); - this.setState({ messageText: '', submitting: false, post_error: null, previews: [], server_error: null, limit_error: null }); + this.setState({messageText: '', submitting: false, postError: null, previews: [], serverError: null}); this.resizePostHolder(); AsyncClient.getPosts(true); - var channel = ChannelStore.get(this.state.channel_id); - var member = ChannelStore.getMember(this.state.channel_id); + var channel = ChannelStore.get(this.state.channelId); + var member = ChannelStore.getMember(this.state.channelId); member.msg_count = channel.total_msg_count; - member.last_viewed_at = (new Date).getTime(); + member.last_viewed_at = Date.now(); ChannelStore.setChannelMember(member); - }.bind(this), function(err) { - var state = {} - state.server_error = err.message; + var state = {}; + state.serverError = err.message; state.submitting = false; this.setState(state); @@ -92,21 +88,21 @@ module.exports = React.createClass({ ); } - $(".post-list-holder-by-time").perfectScrollbar('update'); + $('.post-list-holder-by-time').perfectScrollbar('update'); }, componentDidUpdate: function() { this.resizePostHolder(); }, postMsgKeyPress: function(e) { - if (e.which == 13 && !e.shiftKey && !e.altKey) { + if (e.which === 13 && !e.shiftKey && !e.altKey) { e.preventDefault(); this.refs.textbox.getDOMNode().blur(); this.handleSubmit(e); } - var t = new Date().getTime(); + var t = Date.now(); if ((t - this.lastTime) > 5000) { - SocketStore.sendMessage({channel_id: this.state.channel_id, action: "typing", props: {"parent_id": ""}, state: {} }); + SocketStore.sendMessage({channelId: this.state.channelId, action: 'typing', props: {'parent_id': ''}, state: {}}); this.lastTime = t; } }, @@ -115,64 +111,74 @@ module.exports = React.createClass({ this.setState({messageText: messageText}); var draft = PostStore.getCurrentDraft(); - if (!draft) { - draft = {} - draft['previews'] = []; - draft['uploadsInProgress'] = 0; - } draft['message'] = messageText; PostStore.storeCurrentDraft(draft); }, resizePostHolder: function() { var height = $(window).height() - $(this.refs.topDiv.getDOMNode()).height() - $('#error_bar').outerHeight() - 50; - $(".post-list-holder-by-time").css("height", height + "px"); + $('.post-list-holder-by-time').css('height', height + 'px'); $(window).trigger('resize'); }, - handleFileUpload: function(newPreviews, channel_id) { - var draft = PostStore.getDraft(channel_id); - if (!draft) { - draft = {} - draft['message'] = ''; - draft['uploadsInProgress'] = 0; - draft['previews'] = []; - } + handleUploadStart: function(clientIds, channelId) { + var draft = PostStore.getDraft(channelId); + + draft['uploadsInProgress'] = draft['uploadsInProgress'].concat(clientIds); + PostStore.storeDraft(channelId, draft); - if (channel_id === this.state.channel_id) { - var num = this.state.uploadsInProgress; - var oldPreviews = this.state.previews; - var previews = oldPreviews.concat(newPreviews); + this.setState({uploadsInProgress: draft['uploadsInProgress']}); + }, + handleFileUploadComplete: function(filenames, clientIds, channelId) { + var draft = PostStore.getDraft(channelId); - draft['previews'] = previews; - draft['uploadsInProgress'] = num-1; - PostStore.storeCurrentDraft(draft); + // remove each finished file from uploads + for (var i = 0; i < clientIds.length; i++) { + var index = draft['uploadsInProgress'].indexOf(clientIds[i]); - this.setState({previews: previews, uploadsInProgress:num-1}); - } else { - draft['previews'] = draft['previews'].concat(newPreviews); - draft['uploadsInProgress'] = draft['uploadsInProgress'] > 0 ? draft['uploadsInProgress'] - 1 : 0; - PostStore.storeDraft(channel_id, draft); + if (index !== -1) { + draft['uploadsInProgress'].splice(index, 1); + } } + + draft['previews'] = draft['previews'].concat(filenames); + PostStore.storeDraft(channelId, draft); + + this.setState({uploadsInProgress: draft['uploadsInProgress'], previews: draft['previews']}); }, - handleUploadError: function(err) { - this.setState({ server_error: err }); + handleUploadError: function(err, clientId) { + var draft = PostStore.getDraft(this.state.channelId); + + var index = draft['uploadsInProgress'].indexOf(clientId); + if (index !== -1) { + draft['uploadsInProgress'].splice(index, 1); + } + + PostStore.storeDraft(this.state.channelId, draft); + + this.setState({uploadsInProgress: draft['uploadsInProgress'], serverError: err}); }, - removePreview: function(filename) { + removePreview: function(id) { var previews = this.state.previews; - for (var i = 0; i < previews.length; i++) { - if (previews[i] === filename) { - previews.splice(i, 1); - break; + var uploadsInProgress = this.state.uploadsInProgress; + + // id can either be the path of an uploaded file or the client id of an in progress upload + var index = previews.indexOf(id); + if (index !== -1) { + previews.splice(index, 1); + } else { + index = uploadsInProgress.indexOf(id); + + if (index !== -1) { + uploadsInProgress.splice(index, 1); + this.refs.fileUpload.cancelUpload(id); } } + var draft = PostStore.getCurrentDraft(); - if (!draft) { - draft = {} - draft['message'] = ''; - draft['uploadsInProgress'] = 0; - } draft['previews'] = previews; + draft['uploadsInProgress'] = uploadsInProgress; PostStore.storeCurrentDraft(draft); - this.setState({previews: previews}); + + this.setState({previews: previews, uploadsInProgress: uploadsInProgress}); }, componentDidMount: function() { ChannelStore.addChangeListener(this._onChange); @@ -182,66 +188,50 @@ module.exports = React.createClass({ ChannelStore.removeChangeListener(this._onChange); }, _onChange: function() { - var channel_id = ChannelStore.getCurrentId(); - if (this.state.channel_id != channel_id) { + var channelId = ChannelStore.getCurrentId(); + if (this.state.channelId !== channelId) { var draft = PostStore.getCurrentDraft(); - var previews = []; - var messageText = ''; - var uploadsInProgress = 0; - if (draft) { - previews = draft['previews']; - messageText = draft['message']; - uploadsInProgress = draft['uploadsInProgress']; - } - this.setState({ channel_id: channel_id, messageText: messageText, initialText: messageText, submitting: false, limit_error: null, server_error: null, post_error: null, previews: previews, uploadsInProgress: uploadsInProgress }); + this.setState({ + channelId: channelId, messageText: draft['message'], initialText: draft['message'], submitting: false, + serverError: null, postError: null, previews: draft['previews'], uploadsInProgress: draft['uploadsInProgress'] + }); } }, getInitialState: function() { PostStore.clearDraftUploads(); var draft = PostStore.getCurrentDraft(); - var previews = []; - var messageText = ''; - if (draft) { - previews = draft['previews']; - messageText = draft['message']; - } - return { channel_id: ChannelStore.getCurrentId(), messageText: messageText, uploadsInProgress: 0, previews: previews, submitting: false, initialText: messageText }; + return { + channelId: ChannelStore.getCurrentId(), messageText: draft['message'], uploadsInProgress: draft['uploadsInProgress'], + previews: draft['previews'], submitting: false, initialText: draft['message'] + }; }, - setUploads: function(val) { - var oldInProgress = this.state.uploadsInProgress - var newInProgress = oldInProgress + val; - - if (newInProgress + this.state.previews.length > Constants.MAX_UPLOAD_FILES) { - newInProgress = Constants.MAX_UPLOAD_FILES - this.state.previews.length; - this.setState({limit_error: "Uploads limited to " + Constants.MAX_UPLOAD_FILES + " files maximum. Please use additional posts for more files."}); + getFileCount: function(channelId) { + if (channelId === this.state.channelId) { + return this.state.previews.length + this.state.uploadsInProgress.length; } else { - this.setState({limit_error: null}); - } - - var numToUpload = newInProgress - oldInProgress; - if (numToUpload <= 0) return 0; + var draft = PostStore.getDraft(channelId); - var draft = PostStore.getCurrentDraft(); - if (!draft) { - draft = {} - draft['message'] = ''; - draft['previews'] = []; + return draft['previews'].length + draft['uploadsInProgress'].length; } - draft['uploadsInProgress'] = newInProgress; - PostStore.storeCurrentDraft(draft); - this.setState({uploadsInProgress: newInProgress}); - - return numToUpload; }, render: function() { + var serverError = null; + if (this.state.serverError) { + serverError = ( + <div className='has-error'> + <label className='control-label'>{this.state.serverError}</label> + </div> + ); + } - var server_error = this.state.server_error ? <div className='has-error'><label className='control-label'>{ this.state.server_error }</label></div> : null; - var post_error = this.state.post_error ? <label className='control-label'>{this.state.post_error}</label> : null; - var limit_error = this.state.limit_error ? <div className='has-error'><label className='control-label'>{this.state.limit_error}</label></div> : null; + var postError = null; + if (this.state.postError) { + postError = <label className='control-label'>{this.state.postError}</label>; + } - var preview = <div/>; - if (this.state.previews.length > 0 || this.state.uploadsInProgress > 0) { + var preview = null; + if (this.state.previews.length > 0 || this.state.uploadsInProgress.length > 0) { preview = ( <FilePreview files={this.state.previews} @@ -250,29 +240,35 @@ module.exports = React.createClass({ ); } + var postFooterClassName = 'post-create-footer'; + if (postError) { + postFooterClassName += ' has-error'; + } + return ( - <form id="create_post" ref="topDiv" role="form" onSubmit={this.handleSubmit}> - <div className="post-create"> - <div className="post-create-body"> + <form id='create_post' ref='topDiv' role='form' onSubmit={this.handleSubmit}> + <div className='post-create'> + <div className='post-create-body'> <Textbox onUserInput={this.handleUserInput} onKeyPress={this.postMsgKeyPress} messageText={this.state.messageText} - createMessage="Write a message..." - channelId={this.state.channel_id} - id="post_textbox" - ref="textbox" /> + createMessage='Write a message...' + channelId={this.state.channelId} + id='post_textbox' + ref='textbox' /> <FileUpload - setUploads={this.setUploads} - onFileUpload={this.handleFileUpload} + ref='fileUpload' + getFileCount={this.getFileCount} + onUploadStart={this.handleUploadStart} + onFileUpload={this.handleFileUploadComplete} onUploadError={this.handleUploadError} /> </div> - <div className={post_error ? 'post-create-footer has-error' : 'post-create-footer'}> - { post_error } - { server_error } - { limit_error } - { preview } - <MsgTyping channelId={this.state.channel_id} parentId=""/> + <div className={postFooterClassName}> + {postError} + {serverError} + {preview} + <MsgTyping channelId={this.state.channelId} parentId=''/> </div> </div> </form> diff --git a/web/react/components/file_preview.jsx b/web/react/components/file_preview.jsx index 7c1db3e10..d1b2f734a 100644 --- a/web/react/components/file_preview.jsx +++ b/web/react/components/file_preview.jsx @@ -10,7 +10,12 @@ var Constants = require('../utils/constants.jsx'); module.exports = React.createClass({ handleRemove: function(e) { var previewDiv = e.target.parentNode.parentNode; - this.props.onRemove(previewDiv.getAttribute('data-filename')); + + if (previewDiv.hasAttribute('data-filename')) { + this.props.onRemove(previewDiv.getAttribute('data-filename')); + } else if (previewDiv.hasAttribute('data-client-id')) { + this.props.onRemove(previewDiv.getAttribute('data-client-id')); + } }, render: function() { var previews = []; @@ -43,13 +48,14 @@ module.exports = React.createClass({ } }.bind(this)); - for (var i = 0; i < this.props.uploadsInProgress; i++) { + this.props.uploadsInProgress.forEach(function(clientId) { previews.push( - <div className="preview-div"> + <div className="preview-div" data-client-id={clientId}> <img className="spinner" src="/static/images/load.gif"/> + <a className="remove-preview" onClick={this.handleRemove}><i className="glyphicon glyphicon-remove"/></a> </div> ); - } + }.bind(this)); return ( <div className="preview-container"> diff --git a/web/react/components/file_upload.jsx b/web/react/components/file_upload.jsx index aee089dbc..b90fa4fd3 100644 --- a/web/react/components/file_upload.jsx +++ b/web/react/components/file_upload.jsx @@ -4,12 +4,18 @@ var client = require('../utils/client.jsx'); var Constants = require('../utils/constants.jsx'); var ChannelStore = require('../stores/channel_store.jsx'); +var utils = require('../utils/utils.jsx'); module.exports = React.createClass({ + getInitialState: function() { + return {requests: {}}; + }, handleChange: function() { var element = $(this.refs.fileInput.getDOMNode()); var files = element.prop('files'); + var channelId = ChannelStore.getCurrentId(); + this.props.onUploadError(null); // This looks redundant, but must be done this way due to @@ -21,50 +27,67 @@ module.exports = React.createClass({ } } - var numToUpload = this.props.setUploads(numFiles); + var numToUpload = Math.min(Constants.MAX_UPLOAD_FILES - this.props.getFileCount(channelId), numFiles); + + if (numFiles > numToUpload) { + this.props.onUploadError('Uploads limited to ' + Constants.MAX_UPLOAD_FILES + ' files maximum. Please use additional posts for more files.'); + } for (var i = 0; i < files.length && i < numToUpload; i++) { if (files[i].size > Constants.MAX_FILE_SIZE) { - this.props.onUploadError("Files must be no more than " + Constants.MAX_FILE_SIZE/1000000 + " MB"); + this.props.onUploadError('Files must be no more than ' + Constants.MAX_FILE_SIZE / 1000000 + ' MB'); continue; } - var channel_id = ChannelStore.getCurrentId(); + // generate a unique id that can be used by other components to refer back to this file upload + var clientId = utils.generateId(); // Prepare data to be uploaded. - formData = new FormData(); - formData.append('channel_id', channel_id); + var formData = new FormData(); + formData.append('channel_id', channelId); formData.append('files', files[i], files[i].name); + formData.append('client_ids', clientId); - client.uploadFile(formData, + var request = client.uploadFile(formData, function(data) { - parsedData = $.parseJSON(data); - this.props.onFileUpload(parsedData['filenames'], channel_id); + var parsedData = $.parseJSON(data); + this.props.onFileUpload(parsedData['filenames'], parsedData['client_ids'], channelId); + + var requests = this.state.requests; + for (var i = 0; i < parsedData['client_ids'].length; i++) { + delete requests[parsedData['client_ids'][i]]; + } + this.setState({requests: requests}); }.bind(this), function(err) { - this.props.setUploads(-1); - this.props.onUploadError(err); + this.props.onUploadError(err, clientId); }.bind(this) ); + + var requests = this.state.requests; + requests[clientId] = request; + this.setState({requests: requests}); + + this.props.onUploadStart([clientId], channelId); } // clear file input for all modern browsers - try{ + try { element[0].value = ''; - if(element.value){ - element[0].type = "text"; - element[0].type = "file"; + if (element.value) { + element[0].type = 'text'; + element[0].type = 'file'; } - }catch(e){} + } catch(e) {} }, componentDidMount: function() { var inputDiv = this.refs.input.getDOMNode(); var self = this; - document.addEventListener("paste", function(e) { + document.addEventListener('paste', function(e) { var textarea = $(inputDiv.parentNode.parentNode).find('.custom-textarea')[0]; - if (textarea != e.target && !$.contains(textarea,e.target)) { + if (textarea !== e.target && !$.contains(textarea, e.target)) { return; } @@ -76,54 +99,110 @@ module.exports = React.createClass({ var numItems = 0; if (items) { for (var i = 0; i < items.length; i++) { - if (items[i].type.indexOf("image") !== -1) { + if (items[i].type.indexOf('image') !== -1) { + var ext = items[i].type.split('/')[1].toLowerCase(); + if (ext === 'jpeg') { + ext = 'jpg'; + } - ext = items[i].type.split("/")[1].toLowerCase(); - ext = ext == 'jpeg' ? 'jpg' : ext; + if (Constants.IMAGE_TYPES.indexOf(ext) < 0) { + continue; + } - if (Constants.IMAGE_TYPES.indexOf(ext) < 0) return; - - numItems++ + numItems++; } } - var numToUpload = self.props.setUploads(numItems); + var numToUpload = Math.min(Constants.MAX_UPLOAD_FILES - self.props.getFileCount(channelId), numItems); + + if (numItems > numToUpload) { + self.props.onUploadError('Uploads limited to ' + Constants.MAX_UPLOAD_FILES + ' files maximum. Please use additional posts for more files.'); + } for (var i = 0; i < items.length && i < numToUpload; i++) { - if (items[i].type.indexOf("image") !== -1) { + if (items[i].type.indexOf('image') !== -1) { var file = items[i].getAsFile(); - ext = items[i].type.split("/")[1].toLowerCase(); - ext = ext == 'jpeg' ? 'jpg' : ext; + var ext = items[i].type.split('/')[1].toLowerCase(); + if (ext === 'jpeg') { + ext = 'jpg'; + } - if (Constants.IMAGE_TYPES.indexOf(ext) < 0) return; + if (Constants.IMAGE_TYPES.indexOf(ext) < 0) { + continue; + } - var channel_id = ChannelStore.getCurrentId(); + var channelId = ChannelStore.getCurrentId(); - formData = new FormData(); - formData.append('channel_id', channel_id); - var d = new Date(); - var hour = d.getHours() < 10 ? "0" + d.getHours() : String(d.getHours()); - var min = d.getMinutes() < 10 ? "0" + d.getMinutes() : String(d.getMinutes()); - formData.append('files', file, "Image Pasted at "+d.getFullYear()+"-"+d.getMonth()+"-"+d.getDate()+" "+hour+"-"+min+"." + ext); + // generate a unique id that can be used by other components to refer back to this file upload + var clientId = utils.generateId(); + + var formData = new FormData(); + formData.append('channel_id', channelId); - client.uploadFile(formData, + var d = new Date(); + var hour; + if (d.getHours() < 10) { + hour = '0' + d.getHours(); + } else { + hour = String(d.getHours()); + } + var min; + if (d.getMinutes() < 10) { + min = '0' + d.getMinutes(); + } else { + min = String(d.getMinutes()); + } + + var name = 'Image Pasted at ' + d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate() + ' ' + hour + '-' + min + '.' + ext; + formData.append('files', file, name); + formData.append('client_ids', clientId); + + var request = client.uploadFile(formData, function(data) { - parsedData = $.parseJSON(data); - self.props.onFileUpload(parsedData['filenames'], channel_id); - }.bind(this), + var parsedData = $.parseJSON(data); + self.props.onFileUpload(parsedData['filenames'], parsedData['client_ids'], channelId); + + var requests = self.state.requests; + for (var i = 0; i < parsedData['client_ids'].length; i++) { + delete requests[parsedData['client_ids'][i]]; + } + self.setState({requests: requests}); + }, function(err) { - self.props.onUploadError(err); - }.bind(this) + self.props.onUploadError(err, clientId); + } ); + + var requests = self.state.requests; + requests[clientId] = request; + self.setState({requests: requests}); + + self.props.onUploadStart([clientId], channelId); } } } }); }, + cancelUpload: function(clientId) { + var requests = this.state.requests; + var request = requests[clientId]; + + if (request) { + request.abort(); + + delete requests[clientId]; + this.setState({requests: requests}); + } + }, render: function() { return ( - <span ref="input" className="btn btn-file"><span><i className="glyphicon glyphicon-paperclip"></i></span><input ref="fileInput" type="file" onChange={this.handleChange} multiple/></span> + <span ref='input' className='btn btn-file'> + <span> + <i className='glyphicon glyphicon-paperclip' /> + </span> + <input ref='fileInput' type='file' onChange={this.handleChange} multiple/> + </span> ); } }); diff --git a/web/react/components/invite_member_modal.jsx b/web/react/components/invite_member_modal.jsx index 3eca79bae..75538c8fe 100644 --- a/web/react/components/invite_member_modal.jsx +++ b/web/react/components/invite_member_modal.jsx @@ -256,7 +256,7 @@ module.exports = React.createClass({ parent_id='invite_member' title='Discard Invitations?' message='You have unsent invitations, are you sure you want to discard them?' - confirm_button='Yes, Discard/' + confirm_button='Yes, Discard' /> </div> ); diff --git a/web/react/components/mention_list.jsx b/web/react/components/mention_list.jsx index 5f1bb6d0e..f562cfb29 100644 --- a/web/react/components/mention_list.jsx +++ b/web/react/components/mention_list.jsx @@ -81,7 +81,7 @@ module.exports = React.createClass({ this.setState({selectedMention: 0, selectedUsername: ''}); } }, - onListenerChange: function(id, mentionText, excludeList) { + onListenerChange: function(id, mentionText) { if (id !== this.props.id) { return; } @@ -90,9 +90,6 @@ module.exports = React.createClass({ if (mentionText != null) { newState.mentionText = mentionText; } - if (excludeList != null) { - newState.excludeUsers = excludeList; - } this.setState(newState); }, @@ -149,15 +146,6 @@ module.exports = React.createClass({ scrollTop: scrollAmount }, 75); }, - alreadyMentioned: function(username) { - var excludeUsers = this.state.excludeUsers; - for (var i = 0; i < excludeUsers.length; i++) { - if (excludeUsers[i] === username) { - return true; - } - } - return false; - }, getInitialState: function() { return {excludeUsers: [], mentionText: '-1', selectedMention: 0, selectedUsername: ''}; }, @@ -201,9 +189,6 @@ module.exports = React.createClass({ var index = 0; for (var i = 0; i < users.length && index < MAX_ITEMS_IN_LIST; i++) { - if (this.alreadyMentioned(users[i].username)) { - continue; - } if ((users[i].first_name && users[i].first_name.lastIndexOf(mentionText, 0) === 0) || (users[i].last_name && users[i].last_name.lastIndexOf(mentionText, 0) === 0) || users[i].username.lastIndexOf(mentionText, 0) === 0) { diff --git a/web/react/components/post_list.jsx b/web/react/components/post_list.jsx index bb1b1704c..83f806b79 100644 --- a/web/react/components/post_list.jsx +++ b/web/react/components/post_list.jsx @@ -439,7 +439,7 @@ module.exports = React.createClass({ currentPostDay = utils.getDateForUnixTicks(post.create_at); if (currentPostDay.toDateString() != previousPostDay.toDateString()) { postCtls.push( - <div className="date-separator"> + <div key={currentPostDay.toDateString()} className="date-separator"> <hr className="separator__hr" /> <div className="separator__text">{currentPostDay.toDateString()}</div> </div> @@ -449,7 +449,7 @@ module.exports = React.createClass({ if (post.create_at > last_viewed && !rendered_last_viewed) { rendered_last_viewed = true; postCtls.push( - <div className="new-separator"> + <div key="unviewed" className="new-separator"> <hr id="new_message" className="separator__hr" /> <div className="separator__text">New Messages</div> </div> diff --git a/web/react/components/settings_sidebar.jsx b/web/react/components/settings_sidebar.jsx index ae8510cf2..b4d291622 100644 --- a/web/react/components/settings_sidebar.jsx +++ b/web/react/components/settings_sidebar.jsx @@ -4,6 +4,7 @@ var utils = require('../utils/utils.jsx'); module.exports = React.createClass({ + displayName:'SettingsSidebar', updateTab: function(tab) { this.props.updateTab(tab); $('.settings-modal').addClass('display--content'); @@ -14,7 +15,7 @@ module.exports = React.createClass({ <div className=""> <ul className="nav nav-pills nav-stacked"> {this.props.tabs.map(function(tab) { - return <li className={self.props.activeTab == tab.name ? 'active' : ''}><a href="#" onClick={function(){self.updateTab(tab.name);}}><i className={tab.icon}></i>{tab.ui_name}</a></li> + return <li key={tab.name+'_li'} className={self.props.activeTab == tab.name ? 'active' : ''}><a key={tab.name + '_a'} href="#" onClick={function(){self.updateTab(tab.name);}}><i key={tab.name+'_i'} className={tab.icon}></i>{tab.ui_name}</a></li> })} </ul> </div> diff --git a/web/react/components/sidebar.jsx b/web/react/components/sidebar.jsx index 1d39f5f67..fe73cbcf7 100644 --- a/web/react/components/sidebar.jsx +++ b/web/react/components/sidebar.jsx @@ -56,7 +56,6 @@ function getStateFromStores() { var channelMember = members[channel.id]; var msgCount = channel.total_msg_count - channelMember.msg_count; if (msgCount > 0) { - channel.unread = msgCount; showDirectChannels.push(channel); } else if (currentId === channel.id) { showDirectChannels.push(channel); @@ -70,6 +69,7 @@ function getStateFromStores() { tempChannel.display_name = utils.getDisplayName(teammate); tempChannel.status = UserStore.getStatus(teammate.id); tempChannel.last_post_at = 0; + tempChannel.total_msg_count = 0; readDirectChannels.push(tempChannel); } } @@ -132,11 +132,17 @@ module.exports = React.createClass({ $('.nav-pills__container').perfectScrollbar(); this.updateTitle(); + this.updateUnreadIndicators(); + + $(window).on('resize', this.onResize); }, componentDidUpdate: function() { this.updateTitle(); + this.updateUnreadIndicators(); }, componentWillUnmount: function() { + $(window).off('resize', this.onResize); + ChannelStore.removeChangeListener(this.onChange); UserStore.removeChangeListener(this.onChange); UserStore.removeStatusesChangeListener(this.onChange); @@ -157,7 +163,10 @@ module.exports = React.createClass({ } if (UserStore.getCurrentId() !== msg.user_id) { - var mentions = msg.props.mentions ? JSON.parse(msg.props.mentions) : []; + var mentions = []; + if (msg.props.mentions) { + mentions = JSON.parse(msg.props.mentions); + } var channel = ChannelStore.get(msg.channel_id); var user = UserStore.getCurrentUser(); @@ -175,7 +184,10 @@ module.exports = React.createClass({ username = UserStore.getProfile(msg.user_id).username; } - var title = channel ? channel.display_name : 'Posted'; + var title = 'Posted'; + if (channel) { + title = channel.display_name; + } var repRegex = new RegExp('<br>', 'g'); var post = JSON.parse(msg.props.post); @@ -235,103 +247,143 @@ module.exports = React.createClass({ } } }, + onScroll: function(e) { + this.updateUnreadIndicators(); + }, + onResize: function(e) { + this.updateUnreadIndicators(); + }, + updateUnreadIndicators: function() { + var container = $(this.refs.container.getDOMNode()); + + if (this.firstUnreadChannel) { + var firstUnreadElement = $(this.refs[this.firstUnreadChannel].getDOMNode()); + + if (firstUnreadElement.position().top + firstUnreadElement.height() < 0) { + $(this.refs.topUnreadIndicator.getDOMNode()).css('display', 'initial'); + } else { + $(this.refs.topUnreadIndicator.getDOMNode()).css('display', 'none'); + } + } + + if (this.lastUnreadChannel) { + var lastUnreadElement = $(this.refs[this.lastUnreadChannel].getDOMNode()); + + if (lastUnreadElement.position().top > container.height()) { + $(this.refs.bottomUnreadIndicator.getDOMNode()).css('bottom', '0'); + $(this.refs.bottomUnreadIndicator.getDOMNode()).css('display', 'initial'); + } else { + $(this.refs.bottomUnreadIndicator.getDOMNode()).css('display', 'none'); + } + } + }, getInitialState: function() { return getStateFromStores(); }, render: function() { var members = this.state.members; - var newsActive = window.location.pathname === '/' ? 'active' : ''; + var activeId = this.state.active_id; var badgesActive = false; + + // keep track of the first and last unread channels so we can use them to set the unread indicators var self = this; - var channelItems = this.state.channels.map(function(channel) { - if (channel.type != 'O') { - return ''; - } + this.firstUnreadChannel = null; + this.lastUnreadChannel = null; + function createChannelElement(channel) { var channelMember = members[channel.id]; - var active = channel.id === self.state.active_id ? 'active' : ''; - var msgCount = channel.total_msg_count - channelMember.msg_count; - var titleClass = ''; - if (msgCount > 0 && channelMember.notify_level !== 'quiet') { - titleClass = 'unread-title'; + var linkClass = ''; + if (channel.id === self.state.active_id) { + linkClass = 'active'; } - var badge = ''; - if (channelMember.mention_count > 0) { - badge = <span className='badge pull-right small'>{channelMember.mention_count}</span>; - badgesActive = true; - titleClass = 'unread-title'; + var unread = false; + if (channelMember) { + var msgCount = channel.total_msg_count - channelMember.msg_count; + unread = (msgCount > 0 && channelMember.notify_level !== 'quiet') || channelMember.mention_count > 0; } - return ( - <li key={channel.id} className={active}><a className={'sidebar-channel ' + titleClass} href='#' onClick={function(e){e.preventDefault(); utils.switchChannel(channel);}}>{badge}{channel.display_name}</a></li> - ); - }); + var titleClass = ''; + if (unread) { + titleClass = 'unread-title'; - var privateChannelItems = this.state.channels.map(function(channel) { - if (channel.type !== 'P') { - return ''; + if (!self.firstUnreadChannel) { + self.firstUnreadChannel = channel.name; + } + self.lastUnreadChannel = channel.name; } - var channelMember = members[channel.id]; - var active = channel.id === self.state.active_id ? 'active' : ''; + var badge = null; + if (channelMember) { + if (channel.type === 'D') { + // direct message channels show badges for any number of unread posts + var msgCount = channel.total_msg_count - channelMember.msg_count; + if (msgCount > 0) { + badge = <span className='badge pull-right small'>{msgCount}</span>; + badgesActive = true; + } + } else if (channelMember.mention_count > 0) { + // public and private channels only show badges for mentions + badge = <span className='badge pull-right small'>{channelMember.mention_count}</span>; + badgesActive = true; + } + } - var msgCount = channel.total_msg_count - channelMember.msg_count; - var titleClass = '' - if (msgCount > 0 && channelMember.notify_level !== 'quiet') { - titleClass = 'unread-title' + // set up status icon for direct message channels + var status = null; + if (channel.type === 'D') { + var statusIcon = ''; + if (channel.status === 'online') { + statusIcon = Constants.ONLINE_ICON_SVG; + } else if (channel.status === 'away') { + statusIcon = Constants.ONLINE_ICON_SVG; + } else { + statusIcon = Constants.OFFLINE_ICON_SVG; + } + status = <span className='status' dangerouslySetInnerHTML={{__html: statusIcon}} />; } - var badge = ''; - if (channelMember.mention_count > 0) { - badge = <span className='badge pull-right small'>{channelMember.mention_count}</span>; - badgesActive = true; - titleClass = 'unread-title'; + // set up click handler to switch channels (or create a new channel for non-existant ones) + var clickHandler = null; + var href; + if (!channel.fake) { + clickHandler = function(e) { + e.preventDefault(); + utils.switchChannel(channel); + }; + href = '#'; + } else { + href = TeamStore.getCurrentTeamUrl() + '/channels/' + channel.name; } return ( - <li key={channel.id} className={active}><a className={'sidebar-channel ' + titleClass} href='#' onClick={function(e){e.preventDefault(); utils.switchChannel(channel);}}>{badge}{channel.display_name}</a></li> + <li key={channel.name} ref={channel.name} className={linkClass}> + <a className={'sidebar-channel ' + titleClass} href={href} onClick={clickHandler}> + {status} + {badge} + {channel.display_name} + </a> + </li> ); - }); - - var directMessageItems = this.state.showDirectChannels.map(function(channel) { - var badge = ''; - var titleClass = ''; + }; - var statusIcon = ''; - if (channel.status === 'online') { - statusIcon = Constants.ONLINE_ICON_SVG; - } else if (channel.status === 'away') { - statusIcon = Constants.ONLINE_ICON_SVG; - } else { - statusIcon = Constants.OFFLINE_ICON_SVG; + // create elements for all 3 types of channels + var channelItems = this.state.channels.filter( + function(channel) { + return channel.type === 'O'; } + ).map(createChannelElement); - if (!channel.fake) { - var active = channel.id === self.state.active_id ? 'active' : ''; - - if (channel.unread) { - badge = <span className='badge pull-right small'>{channel.unread}</span>; - badgesActive = true; - titleClass = 'unread-title'; - } - - function handleClick(e) { - e.preventDefault(); - utils.switchChannel(channel, channel.teammate_username); - } - - return ( - <li key={channel.name} className={active}><a className={'sidebar-channel ' + titleClass} href='#' onClick={handleClick}><span className='status' dangerouslySetInnerHTML={{__html: statusIcon}} /> {badge}{channel.display_name}</a></li> - ); - } else { - return ( - <li key={channel.name} className={active}><a className={'sidebar-channel ' + titleClass} href={TeamStore.getCurrentTeamUrl() + '/channels/' + channel.name}><span className='status' dangerouslySetInnerHTML={{__html: statusIcon}} /> {badge}{channel.display_name}</a></li> - ); + var privateChannelItems = this.state.channels.filter( + function(channel) { + return channel.type === 'P'; } - }); + ).map(createChannelElement); + + var directMessageItems = this.state.showDirectChannels.map(createChannelElement); + // update the favicon to show if there are any notifications var link = document.createElement('link'); link.type = 'image/x-icon'; link.rel = 'shortcut icon'; @@ -348,19 +400,26 @@ module.exports = React.createClass({ } head.appendChild(link); - if (channelItems.length == 0) { - <li><small>Loading...</small></li> + var directMessageMore = null; + if (this.state.hideDirectChannels.length > 0) { + directMessageMore = ( + <li> + <a href='#' data-toggle='modal' className='nav-more' data-target='#more_direct_channels' data-channels={JSON.stringify(this.state.hideDirectChannels)}> + {'More ('+this.state.hideDirectChannels.length+')'} + </a> + </li> + ); } - if (privateChannelItems.length == 0) { - <li><small>Loading...</small></li> - } return ( <div> <SidebarHeader teamDisplayName={this.props.teamDisplayName} teamType={this.props.teamType} /> <SearchBox /> - <div className='nav-pills__container'> + <div ref='topUnreadIndicator' className='nav-pills__unread-indicator nav-pills__unread-indicator-top' style={{display: 'none'}}>Unread post(s) above</div> + <div ref='bottomUnreadIndicator' className='nav-pills__unread-indicator nav-pills__unread-indicator-bottom' style={{display: 'none'}}>Unread post(s) below</div> + + <div ref='container' className='nav-pills__container' onScroll={this.onScroll}> <ul className='nav nav-pills nav-stacked'> <li><h4>Channels<a className='add-channel-btn' href='#' data-toggle='modal' data-target='#new_channel' data-channeltype='O'>+</a></h4></li> {channelItems} @@ -374,9 +433,7 @@ module.exports = React.createClass({ <ul className='nav nav-pills nav-stacked'> <li><h4>Private Messages</h4></li> {directMessageItems} - { this.state.hideDirectChannels.length > 0 ? - <li><a href='#' data-toggle='modal' className='nav-more' data-target='#more_direct_channels' data-channels={JSON.stringify(this.state.hideDirectChannels)}>{'More ('+this.state.hideDirectChannels.length+')'}</a></li> - : '' } + {directMessageMore} </ul> </div> </div> diff --git a/web/react/components/sidebar_header.jsx b/web/react/components/sidebar_header.jsx index 72b8547e5..cc3f255ee 100644 --- a/web/react/components/sidebar_header.jsx +++ b/web/react/components/sidebar_header.jsx @@ -87,7 +87,7 @@ var NavbarDropdown = React.createClass({ } }); } - teams.push(<li><a href={utils.getWindowLocationOrigin() + '/signup_team'}>Create a New Team</a></li>); + teams.push(<li key='newTeam_li'><a key='newTeam_a' href={utils.getWindowLocationOrigin() + '/signup_team' }>Create a New Team</a></li>); return ( <ul className='nav navbar-nav navbar-right'> diff --git a/web/react/components/textbox.jsx b/web/react/components/textbox.jsx index bbd1f84b6..b5c5cc564 100644 --- a/web/react/components/textbox.jsx +++ b/web/react/components/textbox.jsx @@ -2,11 +2,7 @@ // See License.txt for license information. var AppDispatcher = require('../dispatcher/app_dispatcher.jsx'); -var UserStore = require('../stores/user_store.jsx'); var PostStore = require('../stores/post_store.jsx'); -var SocketStore = require('../stores/socket_store.jsx'); -var MsgTyping = require('./msg_typing.jsx'); -var MentionList = require('./mention_list.jsx'); var CommandList = require('./command_list.jsx'); var ErrorStore = require('../stores/error_store.jsx'); var AsyncClient = require('../utils/async_client.jsx'); @@ -19,53 +15,53 @@ function getStateFromStores() { var error = ErrorStore.getLastError(); if (error) { - return { message: error.message }; - } else { - return { message: null }; + return {message: error.message}; } + return {message: null}; } module.exports = React.createClass({ + displayName: 'Textbox', caret: -1, addedMention: false, doProcessMentions: false, mentions: [], componentDidMount: function() { - PostStore.addAddMentionListener(this._onChange); - ErrorStore.addChangeListener(this._onError); + PostStore.addAddMentionListener(this.onListenerChange); + ErrorStore.addChangeListener(this.onRecievedError); this.resize(); - this.processMentions(); + this.updateMentionTab(null); }, componentWillUnmount: function() { - PostStore.removeAddMentionListener(this._onChange); - ErrorStore.removeChangeListener(this._onError); + PostStore.removeAddMentionListener(this.onListenerChange); + ErrorStore.removeChangeListener(this.onRecievedError); }, - _onChange: function(id, username) { - if (id !== this.props.id) return; - this.addMention(username); + onListenerChange: function(id, username) { + if (id === this.props.id) { + this.addMention(username); + } }, - _onError: function() { + onRecievedError: function() { var errorState = getStateFromStores(); if (this.state.timerInterrupt != null) { window.clearInterval(this.state.timerInterrupt); - this.setState({ timerInterrupt: null }); + this.setState({timerInterrupt: null}); } - if (errorState.message === "There appears to be a problem with your internet connection") { - this.setState({ connection: "bad-connection" }); - var timerInterrupt = window.setInterval(this._onTimerInterrupt, 5000); - this.setState({ timerInterrupt: timerInterrupt }); - } - else { - this.setState({ connection: "" }); + if (errorState.message === 'There appears to be a problem with your internet connection') { + this.setState({connection: 'bad-connection'}); + var timerInterrupt = window.setInterval(this.onTimerInterrupt, 5000); + this.setState({timerInterrupt: timerInterrupt}); + } else { + this.setState({connection: ''}); } }, - _onTimerInterrupt: function() { + onTimerInterrupt: function() { //Since these should only happen when you have no connection and slightly briefly after any //performance hit should not matter - if (this.state.connection === "bad-connection") { + if (this.state.connection === 'bad-connection') { AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_ERROR, err: null @@ -75,15 +71,15 @@ module.exports = React.createClass({ } window.clearInterval(this.state.timerInterrupt); - this.setState({ timerInterrupt: null }); + this.setState({timerInterrupt: null}); }, componentDidUpdate: function() { if (this.caret >= 0) { - utils.setCaretPosition(this.refs.message.getDOMNode(), this.caret) + utils.setCaretPosition(this.refs.message.getDOMNode(), this.caret); this.caret = -1; } if (this.doProcessMentions) { - this.processMentions(); + this.updateMentionTab(null); this.doProcessMentions = false; } this.resize(); @@ -93,7 +89,7 @@ module.exports = React.createClass({ this.checkForNewMention(nextProps.messageText); } var text = this.refs.message.getDOMNode().value; - if (nextProps.channelId != this.props.channelId || nextProps.messageText !== text) { + if (nextProps.channelId !== this.props.channelId || nextProps.messageText !== text) { this.doProcessMentions = true; } this.addedMention = false; @@ -101,17 +97,17 @@ module.exports = React.createClass({ this.resize(); }, getInitialState: function() { - return { mentionText: '-1', mentions: [], connection: "", timerInterrupt: null }; + return {mentionText: '-1', mentions: [], connection: '', timerInterrupt: null}; }, - updateMentionTab: function(mentionText, excludeList) { + updateMentionTab: function(mentionText) { var self = this; + // using setTimeout so dispatch isn't called during an in progress dispatch setTimeout(function() { AppDispatcher.handleViewAction({ type: ActionTypes.RECIEVED_MENTION_DATA, id: self.props.id, - mention_text: mentionText, - exclude_list: excludeList + mention_text: mentionText }); }, 1); }, @@ -122,13 +118,13 @@ module.exports = React.createClass({ handleKeyPress: function(e) { var text = this.refs.message.getDOMNode().value; - if (!this.refs.commands.isEmpty() && text.indexOf("/") == 0 && e.which==13) { + if (!this.refs.commands.isEmpty() && text.indexOf('/') === 0 && e.which === 13) { this.refs.commands.addFirstCommand(); e.preventDefault(); return; } - if ( !this.doProcessMentions) { + if (!this.doProcessMentions) { var caret = utils.getCaretPosition(this.refs.message.getDOMNode()); var preText = text.substring(0, caret); var lastSpace = preText.lastIndexOf(' '); @@ -150,13 +146,15 @@ module.exports = React.createClass({ this.handleBackspace(e); } }, - handleBackspace: function(e) { + handleBackspace: function() { var text = this.refs.message.getDOMNode().value; - if (text.indexOf("/") == 0) { - this.refs.commands.getSuggestedCommands(text.substring(0, text.length-1)); + if (text.indexOf('/') === 0) { + this.refs.commands.getSuggestedCommands(text.substring(0, text.length - 1)); } - if (this.doProcessMentions) return; + if (this.doProcessMentions) { + return; + } var caret = utils.getCaretPosition(this.refs.message.getDOMNode()); var preText = text.substring(0, caret); @@ -167,57 +165,6 @@ module.exports = React.createClass({ this.doProcessMentions = true; } }, - processMentions: function() { - /* First, find all the possible mentions and add - them all to a list of mentions */ - var text = utils.insertHtmlEntities(this.refs.message.getDOMNode().value); - - var profileMap = UserStore.getProfilesUsernameMap(); - - var re1 = /@([a-z0-9_]+)( |$|\n)/gi; - - var matches = text.match(re1); - - if (!matches) { - this.updateMentionTab(null, []); - return; - } - - var mentions = []; - for (var i = 0; i < matches.length; i++) { - var m = matches[i].substring(1,matches[i].length).trim(); - if ((m in profileMap && mentions.indexOf(m) === -1) || Constants.SPECIAL_MENTIONS.indexOf(m) !== -1) { - mentions.push(m); - } - } - - /* Figure out what the user is currently typing. If it's a mention then we don't - want to add it to the mention list yet, so we remove it if - there is only one occurence of that mention so far. */ - var caret = utils.getCaretPosition(this.refs.message.getDOMNode()); - - var text = this.props.messageText; - - var preText = text.substring(0, caret); - - var atIndex = preText.lastIndexOf('@'); - var spaceIndex = preText.lastIndexOf(' '); - var newLineIndex = preText.lastIndexOf('\n'); - - var typingMention = ""; - if (atIndex > spaceIndex && atIndex > newLineIndex) { - - typingMention = text.substring(atIndex+1, caret); - } - - var re2 = new RegExp('@' + typingMention + '( |$|\n)', 'g'); - - if ((text.match(re2) || []).length === 1 && mentions.indexOf(typingMention) !== -1) { - mentions.splice(mentions.indexOf(typingMention), 1); - } - - this.updateMentionTab(null, mentions); - }, checkForNewMention: function(text) { var caret = utils.getCaretPosition(this.refs.message.getDOMNode()); @@ -227,7 +174,7 @@ module.exports = React.createClass({ // The @ character not typed, so nothing to do. if (atIndex === -1) { - this.updateMentionTab('-1', null); + this.updateMentionTab('-1'); return; } @@ -236,13 +183,13 @@ module.exports = React.createClass({ // If there is a space after the last @, nothing to do. if (lastSpace > atIndex || lastCharSpace > atIndex) { - this.updateMentionTab('-1', null); + this.updateMentionTab('-1'); return; } // Get the name typed so far. - var name = preText.substring(atIndex+1, preText.length).toLowerCase(); - this.updateMentionTab(name, null); + var name = preText.substring(atIndex + 1, preText.length).toLowerCase(); + this.updateMentionTab(name); }, addMention: function(name) { var caret = utils.getCaretPosition(this.refs.message.getDOMNode()); @@ -264,7 +211,7 @@ module.exports = React.createClass({ this.addedMention = true; this.doProcessMentions = true; - this.props.onUserInput(prefix + "@" + name + " " + suffix); + this.props.onUserInput(prefix + '@' + name + ' ' + suffix); }, addCommand: function(cmd) { var elm = this.refs.message.getDOMNode(); @@ -275,22 +222,26 @@ module.exports = React.createClass({ var e = this.refs.message.getDOMNode(); var w = this.refs.wrapper.getDOMNode(); - var lht = parseInt($(e).css('lineHeight'),10); + var lht = parseInt($(e).css('lineHeight'), 10); var lines = e.scrollHeight / lht; - var mod = lines < 2.5 || this.props.messageText === "" ? 30 : 15; + var mod = 15; + + if (lines < 2.5 || this.props.messageText === '') { + mod = 30; + } if (e.scrollHeight - mod < 167) { - $(e).css({'height':'auto','overflow-y':'hidden'}).height(e.scrollHeight - mod); - $(w).css({'height':'auto'}).height(e.scrollHeight+2); + $(e).css({height: 'auto', 'overflow-y': 'hidden'}).height(e.scrollHeight - mod); + $(w).css({height: 'auto'}).height(e.scrollHeight + 2); } else { - $(e).css({'height':'auto','overflow-y':'scroll'}).height(167); - $(w).css({'height':'auto'}).height(167); + $(e).css({height: 'auto', 'overflow-y': 'scroll'}).height(167); + $(w).css({height: 'auto'}).height(167); } }, handleFocus: function() { var elm = this.refs.message.getDOMNode(); if (elm.title === elm.value) { - elm.value = ""; + elm.value = ''; } }, handleBlur: function() { @@ -304,9 +255,9 @@ module.exports = React.createClass({ }, render: function() { return ( - <div ref="wrapper" className="textarea-wrapper"> + <div ref='wrapper' className='textarea-wrapper'> <CommandList ref='commands' addCommand={this.addCommand} channelId={this.props.channelId} /> - <textarea id={this.props.id} ref="message" className={"form-control custom-textarea " + this.state.connection} spellCheck="true" autoComplete="off" autoCorrect="off" rows="1" placeholder={this.props.createMessage} value={this.props.messageText} onInput={this.handleChange} onChange={this.handleChange} onKeyPress={this.handleKeyPress} onKeyDown={this.handleKeyDown} onFocus={this.handleFocus} onBlur={this.handleBlur} onPaste={this.handlePaste} /> + <textarea id={this.props.id} ref='message' className={'form-control custom-textarea ' + this.state.connection} spellCheck='true' autoComplete='off' autoCorrect='off' rows='1' placeholder={this.props.createMessage} value={this.props.messageText} onInput={this.handleChange} onChange={this.handleChange} onKeyPress={this.handleKeyPress} onKeyDown={this.handleKeyDown} onFocus={this.handleFocus} onBlur={this.handleBlur} onPaste={this.handlePaste} /> </div> ); } diff --git a/web/react/components/view_image.jsx b/web/react/components/view_image.jsx index 4b2f8f650..dc85b53e5 100644 --- a/web/react/components/view_image.jsx +++ b/web/react/components/view_image.jsx @@ -5,113 +5,143 @@ var Client = require('../utils/client.jsx'); var utils = require('../utils/utils.jsx'); module.exports = React.createClass({ - displayName: "ViewImageModal", + displayName: 'ViewImageModal', canSetState: false, handleNext: function() { var id = this.state.imgId + 1; - if (id > this.props.filenames.length-1) { + if (id > this.props.filenames.length - 1) { id = 0; } - this.setState({ imgId: id }); + this.setState({imgId: id}); this.loadImage(id); }, handlePrev: function() { var id = this.state.imgId - 1; if (id < 0) { - id = this.props.filenames.length-1; + id = this.props.filenames.length - 1; } - this.setState({ imgId: id }); + this.setState({imgId: id}); this.loadImage(id); }, + handleKeyPress: function handleKeyPress(e) { + if (!e) { + return; + } else if (e.keyCode === 39) { + this.handleNext(); + } else if (e.keyCode === 37) { + this.handlePrev(); + } + }, componentWillReceiveProps: function(nextProps) { - this.setState({ imgId: nextProps.startId }); + this.setState({imgId: nextProps.startId}); }, loadImage: function(id) { - var imgHeight = $(window).height()-100; - if (this.state.loaded[id] || this.state.images[id]){ - $('.modal .modal-image .image-wrapper img').css("max-height",imgHeight); + var imgHeight = $(window).height() - 100; + if (this.state.loaded[id] || this.state.images[id]) { + $('.modal .modal-image .image-wrapper img').css('max-height', imgHeight); return; - }; + } var filename = this.props.filenames[id]; var fileInfo = utils.splitFileLocation(filename); var fileType = utils.getFileType(fileInfo.ext); - if (fileType === "image") { + if (fileType === 'image') { var self = this; var img = new Image(); img.load(this.getPreviewImagePath(filename), - function(){ + function() { var progress = self.state.progress; progress[id] = img.completedPercentage; - self.setState({ progress: progress }); - }); + self.setState({progress: progress}); + }); img.onload = function(imgid) { return function() { var loaded = self.state.loaded; loaded[imgid] = true; - self.setState({ loaded: loaded }); - $(self.refs.image.getDOMNode()).css("max-height",imgHeight); + self.setState({loaded: loaded}); + $(self.refs.image.getDOMNode()).css('max-height', imgHeight); }; }(id); var images = this.state.images; images[id] = img; - this.setState({ images: images }); + this.setState({images: images}); } else { // there's nothing to load for non-image files var loaded = this.state.loaded; loaded[id] = true; - this.setState({ loaded: loaded }); + this.setState({loaded: loaded}); } }, componentDidUpdate: function() { if (this.state.loaded[this.state.imgId]) { if (this.refs.imageWrap) { - $(this.refs.imageWrap.getDOMNode()).removeClass("default"); + $(this.refs.imageWrap.getDOMNode()).removeClass('default'); } } }, componentDidMount: function() { var self = this; - $("#"+this.props.modalId).on('shown.bs.modal', function() { - self.setState({ viewed: true }); + $('#' + this.props.modalId).on('shown.bs.modal', function() { + self.setState({viewed: true}); self.loadImage(self.state.imgId); - }) + }); - $(this.refs.modal.getDOMNode()).click(function(e){ - if (e.target == this || e.target == self.refs.imageBody.getDOMNode()) { + $(this.refs.modal.getDOMNode()).click(function(e) { + if (e.target === this || e.target === self.refs.imageBody.getDOMNode()) { $('.image_modal').modal('hide'); } }); $(this.refs.imageWrap.getDOMNode()).hover( function() { - $(self.refs.imageFooter.getDOMNode()).addClass("footer--show"); + $(self.refs.imageFooter.getDOMNode()).addClass('footer--show'); }, function() { - $(self.refs.imageFooter.getDOMNode()).removeClass("footer--show"); + $(self.refs.imageFooter.getDOMNode()).removeClass('footer--show'); } ); + $(window).on('keyup', this.handleKeyPress); + // keep track of whether or not this component is mounted so we can safely set the state asynchronously this.canSetState = true; }, componentWillUnmount: function() { this.canSetState = false; + $(window).off('keyup', this.handleKeyPress); }, - getPublicLink: function(e) { - data = {}; - data["channel_id"] = this.props.channelId; - data["user_id"] = this.props.userId; - data["filename"] = this.props.filenames[this.state.imgId]; + getPublicLink: function() { + var data = {}; + data.channel_id = this.props.channelId; + data.user_id = this.props.userId; + data.filename = this.props.filenames[this.state.imgId]; Client.getPublicLink(data, - function(data) { - window.open(data["public_link"]); - }.bind(this), - function(err) { - }.bind(this) + function(serverData) { + window.open(serverData.public_link); + }, + function() { + } ); }, + getPreviewImagePath: function(filename) { + // Returns the path to a preview image that can be used to represent a file. + var fileInfo = utils.splitFileLocation(filename); + var fileType = utils.getFileType(fileInfo.ext); + + if (fileType === 'image') { + // This is a temporary patch to fix issue with old files using absolute paths + if (fileInfo.path.indexOf('/api/v1/files/get') !== -1) { + fileInfo.path = fileInfo.path.split('/api/v1/files/get')[1]; + } + fileInfo.path = utils.getWindowLocationOrigin() + '/api/v1/files/get' + fileInfo.path; + + return fileInfo.path + '_preview.jpg'; + } + + // only images have proper previews, so just use a placeholder icon for non-images + return utils.getPreviewImagePathForFileType(fileType); + }, getInitialState: function() { var loaded = []; var progress = []; @@ -119,10 +149,10 @@ module.exports = React.createClass({ loaded.push(false); progress.push(0); } - return { imgId: this.props.startId, viewed: false, loaded: loaded, progress: progress, images: {}, fileSizes: {} }; + return {imgId: this.props.startId, viewed: false, loaded: loaded, progress: progress, images: {}, fileSizes: {}}; }, render: function() { - if (this.props.filenames.length < 1 || this.props.filenames.length-1 < this.state.imgId) { + if (this.props.filenames.length < 1 || this.props.filenames.length - 1 < this.state.imgId) { return <div/>; } @@ -132,34 +162,34 @@ module.exports = React.createClass({ var name = decodeURIComponent(utils.getFileName(filename)); var content; - var bgClass = ""; + var bgClass = ''; if (this.state.loaded[this.state.imgId]) { var fileInfo = utils.splitFileLocation(filename); var fileType = utils.getFileType(fileInfo.ext); - if (fileType === "image") { + if (fileType === 'image') { // image files just show a preview of the file content = ( - <a href={fileUrl} target="_blank"> - <img ref="image" src={this.getPreviewImagePath(filename)}/> + <a href={fileUrl} target='_blank'> + <img ref='image' src={this.getPreviewImagePath(filename)}/> </a> ); } else { // non-image files include a section providing details about the file - var infoString = "File type " + fileInfo.ext.toUpperCase(); + var infoString = 'File type ' + fileInfo.ext.toUpperCase(); if (this.state.fileSizes[filename] && this.state.fileSizes[filename] >= 0) { - infoString += ", Size " + utils.fileSizeToString(this.state.fileSizes[filename]); + infoString += ', Size ' + utils.fileSizeToString(this.state.fileSizes[filename]); } content = ( - <div className="file-details__container"> - <a className={"file-details__preview"} href={fileUrl} target="_blank"> - <span className="file-details__preview-helper" /> - <img ref="image" src={this.getPreviewImagePath(filename)} /> + <div className='file-details__container'> + <a className={'file-details__preview'} href={fileUrl} target='_blank'> + <span className='file-details__preview-helper' /> + <img ref='image' src={this.getPreviewImagePath(filename)} /> </a> - <div className="file-details"> - <div className="file-details__name">{name}</div> - <div className="file-details__info">{infoString}</div> + <div className='file-details'> + <div className='file-details__name'>{name}</div> + <div className='file-details__info'>{infoString}</div> </div> </div> ); @@ -182,68 +212,63 @@ module.exports = React.createClass({ var percentage = Math.floor(this.state.progress[this.state.imgId]); content = ( <div> - <img className="loader-image" src="/static/images/load.gif" /> + <img className='loader-image' src='/static/images/load.gif' /> { percentage > 0 ? - <span className="loader-percent" >{"Previewing " + percentage + "%"}</span> - : ""} + <span className='loader-percent' >{'Previewing ' + percentage + '%'}</span> + : ''} + </div> + ); + bgClass = 'black-bg'; + } + + var publicLink = ''; + if (config.AllowPublicLink) { + publicLink = ( + <div> + <a href='#' className='public-link text' data-title='Public Image' onClick={this.getPublicLink}>Get Public Link</a> + <span className='text'> | </span> </div> ); - bgClass = "black-bg"; + } + + var leftArrow = ''; + var rightArrow = ''; + if (this.props.filenames.length > 1) { + leftArrow = ( + <a className='modal-prev-bar' href='#' onClick={this.handlePrev}> + <i className='image-control image-prev'/> + </a> + ); + + rightArrow = ( + <a className='modal-next-bar' href='#' onClick={this.handleNext}> + <i className='image-control image-next'/> + </a> + ); } return ( - <div className="modal fade image_modal" ref="modal" id={this.props.modalId} tabIndex="-1" role="dialog" aria-hidden="true"> - <div className="modal-dialog modal-image"> - <div className="modal-content image-content"> - <div ref="imageBody" className="modal-body image-body"> - <div ref="imageWrap" className={"image-wrapper default " + bgClass}> - <div className="modal-close" data-dismiss="modal"></div> + <div className='modal fade image_modal' ref='modal' id={this.props.modalId} tabIndex='-1' role='dialog' aria-hidden='true'> + <div className='modal-dialog modal-image'> + <div className='modal-content image-content'> + <div ref='imageBody' className='modal-body image-body'> + <div ref='imageWrap' className={'image-wrapper default ' + bgClass}> + <div className='modal-close' data-dismiss='modal'></div> {content} - <div ref="imageFooter" className="modal-button-bar"> - <span className="pull-left text">{"Image "+(this.state.imgId+1)+" of "+this.props.filenames.length}</span> - <div className="image-links"> - { config.AllowPublicLink ? - <div> - <a href="#" className="public-link text" data-title="Public Image" onClick={this.getPublicLink}>Get Public Link</a> - <span className="text"> | </span> - </div> - : "" } - <a href={fileUrl} download={name} className="text">Download</a> + <div ref='imageFooter' className='modal-button-bar'> + <span className='pull-left text'>{'Image ' + (this.state.imgId + 1) + ' of ' + this.props.filenames.length}</span> + <div className='image-links'> + {publicLink} + <a href={fileUrl} download={name} className='text'>Download</a> </div> </div> </div> - { this.props.filenames.length > 1 ? - <a className="modal-prev-bar" href="#" onClick={this.handlePrev}> - <i className="image-control image-prev"/> - </a> - : "" } - { this.props.filenames.length > 1 ? - <a className="modal-next-bar" href="#" onClick={this.handleNext}> - <i className="image-control image-next"/> - </a> - : "" } + {leftArrow} + {rightArrow} </div> </div> </div> </div> ); - }, - // Returns the path to a preview image that can be used to represent a file. - getPreviewImagePath: function(filename) { - var fileInfo = utils.splitFileLocation(filename); - var fileType = utils.getFileType(fileInfo.ext); - - if (fileType === "image") { - // This is a temporary patch to fix issue with old files using absolute paths - if (fileInfo.path.indexOf("/api/v1/files/get") !== -1) { - fileInfo.path = fileInfo.path.split("/api/v1/files/get")[1]; - } - fileInfo.path = utils.getWindowLocationOrigin() + "/api/v1/files/get" + fileInfo.path; - - return fileInfo.path + '_preview.jpg'; - } else { - // only images have proper previews, so just use a placeholder icon for non-images - return utils.getPreviewImagePathForFileType(fileType); - } } }); |