Files
mattermost/webapp/components/file_upload.jsx
bonespiked 28ad645153 Ticket 4665 - Emoji Picker (#5157)
*  #4665  Added EmojiPicker

Work primarily by @broernr-de and @harrison on pre-release.mattermost.com

* Final fixes to handle custom emojis from internal review and single merge error

* ESLint fixes

* CSS changes and other code to support emoji picker in reply window

* Fix for file upload and emoji picker icon positions on post and comment.

RHS emoji picker appearing see-through at this time.

* Fix for two ESLint issues.

* covered most of feedback:
RHS emoji picker looks correct color-wise
RHS emoji picker dynamically positions against height of thread size (post + reply messages)
escape closes emoji window
search box focused on open

ESLint fixes against other files
oversized emoji preview fixes

* Adding in 'outside click' eventing to dismiss the emoji window

* Changing some formatting to fix mismatch between my local eslant rules and jenkins.

* adding alternative import method due to downstream testing errors

* yet another attempt to retain functionality and pass tests - skipping import of browser store

* fix for feedback items 5 and 7:
* move search to float on top with stylistic changes
* whitespace in the header (+1 squashed commit)
Squashed commits:
[6a26d32] changes that address items
1, 2, 6, 8, and 9 of latest feedback

* Fix for attachment preview location on mobile

* Fix for latest rounds of feedback

* fixing eslint issue

* making emojipicker sprite based, fixing alignments

* Fix for emoji quality, fixing some behavior (hover background and cursor settings)
undoing config changes

* Preview feature for emojis

* Adjustments to config file, and changing layout/design of attachment and emoji icon.

* manual revert from master branch for config.json

* reverting paperclip and fixing alignments.  Additionally fixing inadvertent display of picker on mobile.

* CSS changes to try to fix the hover behavior - currently working for emoji picker (when enabled), but hover for attachment isn't working

* Made suggested changes by jwilander except for jQuery removal

* Adding hover for both icons

* removal of some usages of jQuery

* Fix for two layout issues on IE11/Edge

* UI improvements for emoji picker

* Fix for many minor display issues

* fix for additional appearance items

* fix to two minor UI items

* A little extra padding for IE11

* fix for IE11 scroll issue, and removing align attribute on img tag which was throwing js error

* fixes some display issues on firefox

* fix for uneven sides of emojis

* fix for eslint issues that I didn't introduce

* fix for missing bottom edge of RHS emojipicker.  also fixing text overlapping icons on text area (including RHS)

* Update "emoji selector" to "emoji picker"

* changes for code review
- removal of ..getDOMNode
- use sprite imagery for emoji preview
- remove lastBlurAt from state as it wasn't used

* fixes for:
- fake custom emoji preview in picker
- RHS scrollbar on preview

* fix for minor alignment of preview emoji
2017-03-24 09:09:51 -04:00

402 lines
13 KiB
JavaScript

// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import $ from 'jquery';
import 'jquery-dragster/jquery.dragster.js';
import ReactDOM from 'react-dom';
import Constants from 'utils/constants.jsx';
import ChannelStore from 'stores/channel_store.jsx';
import DelayedAction from 'utils/delayed_action.jsx';
import * as UserAgent from 'utils/user_agent.jsx';
import * as Utils from 'utils/utils.jsx';
import {intlShape, injectIntl, defineMessages} from 'react-intl';
import {uploadFile} from 'actions/file_actions.jsx';
const holders = defineMessages({
limited: {
id: 'file_upload.limited',
defaultMessage: 'Uploads limited to {count} files maximum. Please use additional posts for more files.'
},
filesAbove: {
id: 'file_upload.filesAbove',
defaultMessage: 'Files above {max}MB could not be uploaded: {filenames}'
},
fileAbove: {
id: 'file_upload.fileAbove',
defaultMessage: 'File above {max}MB could not be uploaded: {filename}'
},
pasted: {
id: 'file_upload.pasted',
defaultMessage: 'Image Pasted at '
}
});
import React from 'react';
const OverlayTimeout = 500;
class FileUpload extends React.Component {
constructor(props) {
super(props);
this.uploadFiles = this.uploadFiles.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleDrop = this.handleDrop.bind(this);
this.registerDragEvents = this.registerDragEvents.bind(this);
this.cancelUpload = this.cancelUpload.bind(this);
this.pasteUpload = this.pasteUpload.bind(this);
this.keyUpload = this.keyUpload.bind(this);
this.handleMaxUploadReached = this.handleMaxUploadReached.bind(this);
this.emojiClick = this.emojiClick.bind(this);
this.state = {
requests: {}
};
}
fileUploadSuccess(channelId, data) {
this.props.onFileUpload(data.file_infos, data.client_ids, channelId);
const requests = Object.assign({}, this.state.requests);
for (var j = 0; j < data.client_ids.length; j++) {
Reflect.deleteProperty(requests, data.client_ids[j]);
}
this.setState({requests});
}
fileUploadFail(clientId, channelId, err) {
this.props.onUploadError(err, clientId, channelId);
}
uploadFiles(files) {
// clear any existing errors
this.props.onUploadError(null);
const channelId = this.props.channelId || ChannelStore.getCurrentId();
const uploadsRemaining = Constants.MAX_UPLOAD_FILES - this.props.getFileCount(channelId);
let numUploads = 0;
// keep track of how many files have been too large
const tooLargeFiles = [];
for (let i = 0; i < files.length && numUploads < uploadsRemaining; i++) {
if (files[i].size > global.mm_config.MaxFileSize) {
tooLargeFiles.push(files[i]);
continue;
}
// generate a unique id that can be used by other components to refer back to this upload
const clientId = Utils.generateId();
const request = uploadFile(
files[i],
files[i].name,
channelId,
clientId,
this.fileUploadSuccess.bind(this, channelId),
this.fileUploadFail.bind(this, clientId)
);
const requests = this.state.requests;
requests[clientId] = request;
this.setState({requests});
this.props.onUploadStart([clientId], channelId);
numUploads += 1;
}
const {formatMessage} = this.props.intl;
if (files.length > uploadsRemaining) {
this.props.onUploadError(formatMessage(holders.limited, {count: Constants.MAX_UPLOAD_FILES}));
} else if (tooLargeFiles.length > 1) {
var tooLargeFilenames = tooLargeFiles.map((file) => file.name).join(', ');
this.props.onUploadError(formatMessage(holders.filesAbove, {max: (global.mm_config.MaxFileSize / 1048576), filenames: tooLargeFilenames}));
} else if (tooLargeFiles.length > 0) {
this.props.onUploadError(formatMessage(holders.fileAbove, {max: (global.mm_config.MaxFileSize / 1048576), filename: tooLargeFiles[0].name}));
}
}
handleChange(e) {
if (e.target.files.length > 0) {
this.uploadFiles(e.target.files);
Utils.clearFileInput(e.target);
}
this.props.onFileUploadChange();
}
handleDrop(e) {
this.props.onUploadError(null);
var files = e.originalEvent.dataTransfer.files;
if (typeof files !== 'string' && files.length) {
this.uploadFiles(files);
}
}
componentDidMount() {
if (this.props.postType === 'post') {
this.registerDragEvents('.row.main', '.center-file-overlay');
} else if (this.props.postType === 'comment') {
this.registerDragEvents('.post-right__container', '.right-file-overlay');
}
document.addEventListener('paste', this.pasteUpload);
document.addEventListener('keydown', this.keyUpload);
}
registerDragEvents(containerSelector, overlaySelector) {
const self = this;
const overlay = $(overlaySelector);
const dragTimeout = new DelayedAction(() => {
if (!overlay.hasClass('hidden')) {
overlay.addClass('hidden');
}
});
$(containerSelector).dragster({
enter(dragsterEvent, e) {
var files = e.originalEvent.dataTransfer;
if (Utils.isFileTransfer(files)) {
$(overlaySelector).removeClass('hidden');
}
},
leave(dragsterEvent, e) {
var files = e.originalEvent.dataTransfer;
if (Utils.isFileTransfer(files) && !overlay.hasClass('hidden')) {
overlay.addClass('hidden');
}
dragTimeout.cancel();
},
over() {
dragTimeout.fireAfter(OverlayTimeout);
},
drop(dragsterEvent, e) {
if (!overlay.hasClass('hidden')) {
overlay.addClass('hidden');
}
dragTimeout.cancel();
self.handleDrop(e);
}
});
this.props.onFileUploadChange();
}
componentWillUnmount() {
let target;
if (this.props.postType === 'post') {
target = $('.row.main');
} else {
target = $('.post-right__container');
}
document.removeEventListener('paste', this.pasteUpload);
document.removeEventListener('keydown', this.keyUpload);
// jquery-dragster doesn't provide a function to unregister itself so do it manually
target.off('dragenter dragleave dragover drop dragster:enter dragster:leave dragster:over dragster:drop');
}
emojiClick() {
this.props.onEmojiClick();
}
pasteUpload(e) {
var inputDiv = ReactDOM.findDOMNode(this.refs.input);
const {formatMessage} = this.props.intl;
if (!e.clipboardData || !e.clipboardData.items) {
return;
}
var textarea = $(inputDiv.parentNode.parentNode).find('.custom-textarea')[0];
if (textarea !== e.target && !$.contains(textarea, e.target)) {
return;
}
this.props.onUploadError(null);
const items = [];
for (let i = 0; i < e.clipboardData.items.length; i++) {
const item = e.clipboardData.items[i];
if (item.type.indexOf('image') === -1) {
continue;
}
if (Constants.IMAGE_TYPES.indexOf(item.type.split('/')[1].toLowerCase()) === -1) {
continue;
}
items.push(item);
}
// This looks redundant, but must be done this way due to
// setState being an asynchronous call
if (items) {
var numToUpload = Math.min(Constants.MAX_UPLOAD_FILES - this.props.getFileCount(ChannelStore.getCurrentId()), items.length);
if (items.length > numToUpload) {
this.props.onUploadError(formatMessage(holders.limited, {count: Constants.MAX_UPLOAD_FILES}));
}
const channelId = this.props.channelId || ChannelStore.getCurrentId();
for (var i = 0; i < items.length && i < numToUpload; i++) {
var file = items[i].getAsFile();
var ext = items[i].type.split('/')[1].toLowerCase();
// generate a unique id that can be used by other components to refer back to this file upload
var clientId = Utils.generateId();
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());
}
const name = formatMessage(holders.pasted) + d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + hour + '-' + min + '.' + ext;
const request = uploadFile(
file,
name,
channelId,
clientId,
this.fileUploadSuccess.bind(this, channelId),
this.fileUploadFail.bind(this, clientId)
);
const requests = this.state.requests;
requests[clientId] = request;
this.setState({requests});
this.props.onUploadStart([clientId], channelId);
}
if (numToUpload > 0) {
this.props.onFileUploadChange();
}
}
}
keyUpload(e) {
if (Utils.cmdOrCtrlPressed(e) && e.keyCode === Constants.KeyCodes.U) {
e.preventDefault();
if ((this.props.postType === 'post' && document.activeElement.id === 'post_textbox') ||
(this.props.postType === 'comment' && document.activeElement.id === 'reply_textbox')) {
$(this.refs.fileInput).focus().trigger('click');
}
}
}
cancelUpload(clientId) {
const requests = Object.assign({}, this.state.requests);
const request = requests[clientId];
if (request) {
request.abort();
Reflect.deleteProperty(requests, clientId);
this.setState({requests});
}
}
handleMaxUploadReached(e) {
e.preventDefault();
const {formatMessage} = this.props.intl;
this.props.onUploadError(formatMessage(holders.limited, {count: Constants.MAX_UPLOAD_FILES}));
return false;
}
render() {
let multiple = true;
if (UserAgent.isMobileApp()) {
// iOS WebViews don't upload videos properly in multiple mode
multiple = false;
}
let accept = '';
if (UserAgent.isIosChrome()) {
// iOS Chrome can't upload videos at all
accept = 'image/*';
}
const channelId = this.props.channelId || ChannelStore.getCurrentId();
const uploadsRemaining = Constants.MAX_UPLOAD_FILES - this.props.getFileCount(channelId);
const emojiSpan = (<span
className={'fa fa-smile-o icon--emoji-picker emoji-' + this.props.navBarName}
onClick={this.emojiClick}
/>);
const filestyle = {visibility: 'hidden'};
return (
<span
ref='input'
className={'btn btn-file' + (uploadsRemaining <= 0 ? ' btn-file__disabled' : '')}
>
<div className='icon--attachment'>
<span
dangerouslySetInnerHTML={{__html: Constants.ATTACHMENT_ICON_SVG}}
onClick={() => this.refs.fileInput.click()}
/>
<input
ref='fileInput'
type='file'
style={filestyle}
onChange={this.handleChange}
onClick={uploadsRemaining > 0 ? this.props.onClick : this.handleMaxUploadReached}
multiple={multiple}
accept={accept}
/>
</div>
{this.props.emojiEnabled ? emojiSpan : ''}
</span>
);
}
}
FileUpload.propTypes = {
intl: intlShape.isRequired,
onUploadError: React.PropTypes.func,
getFileCount: React.PropTypes.func,
onClick: React.PropTypes.func,
onFileUpload: React.PropTypes.func,
onUploadStart: React.PropTypes.func,
onFileUploadChange: React.PropTypes.func,
onTextDrop: React.PropTypes.func,
channelId: React.PropTypes.string,
postType: React.PropTypes.string,
onEmojiClick: React.PropTypes.func,
navBarName: React.PropTypes.string,
emojiEnabled: React.PropTypes.bool
};
export default injectIntl(FileUpload, {withRef: true});