PLT-1378 Initial version of emoji reactions (#4520)

* Refactored emoji.json to support multiple aliases and emoji categories

* Added custom category to emoji.jsx and stabilized all fields

* Removed conflicting aliases for :mattermost: and :ca:

* fixup after store changes

* Added emoji reactions

* Removed reactions for an emoji when that emoji is deleted

* Fixed incorrect test case

* Renamed ReactionList to ReactionListView

* Fixed 👍 and 👎 not showing up as possible reactions

* Removed text emoticons from emoji reaction autocomplete

* Changed emoji reactions to be sorted by the order that they were first created

* Set a maximum number of listeners for the ReactionStore

* Removed unused code from Textbox component

* Fixed reaction permissions

* Changed error code when trying to modify reactions for another user

* Fixed merge conflicts

* Properly applied theme colours to reactions

* Fixed ESLint and gofmt errors

* Fixed ReactionListContainer to properly update when its post prop changes

* Removed unnecessary escape characters from reaction regexes

* Shared reaction message pattern between CreatePost and CreateComment

* Removed an unnecessary select query when saving a reaction

* Changed reactions route to be under /reactions

* Fixed copyright dates on newly added files

* Removed debug code that prevented all unit tests from being ran

* Cleaned up unnecessary code for reactions

* Renamed ReactionStore.List to ReactionStore.GetForPost
Этот коммит содержится в:
Harrison Healey
2016-11-30 13:55:49 -05:00
коммит произвёл GitHub
родитель 2bf0342d13
Коммит 165ad0d4f7
47 изменённых файлов: 2154 добавлений и 98 удалений

Просмотреть файл

@@ -252,3 +252,23 @@ export function loadProfilesForPosts(posts) {
AsyncClient.getProfilesByIds(list);
}
export function addReaction(channelId, postId, emojiName) {
const reaction = {
post_id: postId,
user_id: UserStore.getCurrentId(),
emoji_name: emojiName
};
AsyncClient.saveReaction(channelId, reaction);
}
export function removeReaction(channelId, postId, emojiName) {
const reaction = {
post_id: postId,
user_id: UserStore.getCurrentId(),
emoji_name: emojiName
};
AsyncClient.deleteReaction(channelId, reaction);
}

Просмотреть файл

@@ -11,6 +11,7 @@ import BrowserStore from 'stores/browser_store.jsx';
import ErrorStore from 'stores/error_store.jsx';
import NotificationStore from 'stores/notification_store.jsx'; //eslint-disable-line no-unused-vars
import AppDispatcher from 'dispatcher/app_dispatcher.jsx';
import Client from 'client/web_client.jsx';
import WebSocketClient from 'client/web_websocket_client.jsx';
import * as WebrtcActions from './webrtc_actions.jsx';
@@ -23,7 +24,7 @@ import {loadProfilesAndTeamMembersForDMSidebar} from 'actions/user_actions.jsx';
import {loadChannelsForCurrentUser} from 'actions/channel_actions.jsx';
import * as StatusActions from 'actions/status_actions.jsx';
import {Constants, SocketEvents, UserStatuses} from 'utils/constants.jsx';
import {ActionTypes, Constants, SocketEvents, UserStatuses} from 'utils/constants.jsx';
import {browserHistory} from 'react-router/es6';
@@ -165,6 +166,14 @@ function handleEvent(msg) {
handleWebrtc(msg);
break;
case SocketEvents.REACTION_ADDED:
handleReactionAddedEvent(msg);
break;
case SocketEvents.REACTION_REMOVED:
handleReactionRemovedEvent(msg);
break;
default:
}
}
@@ -320,3 +329,23 @@ function handleWebrtc(msg) {
const data = msg.data;
return WebrtcActions.handle(data);
}
function handleReactionAddedEvent(msg) {
const reaction = JSON.parse(msg.data.reaction);
AppDispatcher.handleServerAction({
type: ActionTypes.ADDED_REACTION,
postId: reaction.post_id,
reaction
});
}
function handleReactionRemovedEvent(msg) {
const reaction = JSON.parse(msg.data.reaction);
AppDispatcher.handleServerAction({
type: ActionTypes.REMOVED_REACTION,
postId: reaction.post_id,
reaction
});
}

Просмотреть файл

@@ -2005,11 +2005,11 @@ export default class Client {
removeCertificateFile(filename, success, error) {
request.
post(`${this.getAdminRoute()}/remove_certificate`).
set(this.defaultHeaders).
accept('application/json').
send({filename}).
end(this.handleResponse.bind(this, 'removeCertificateFile', success, error));
post(`${this.getAdminRoute()}/remove_certificate`).
set(this.defaultHeaders).
accept('application/json').
send({filename}).
end(this.handleResponse.bind(this, 'removeCertificateFile', success, error));
}
samlCertificateStatus(success, error) {
@@ -2030,6 +2030,33 @@ export default class Client {
});
}
saveReaction(channelId, reaction, success, error) {
request.
post(`${this.getChannelNeededRoute(channelId)}/posts/${reaction.post_id}/reactions/save`).
set(this.defaultHeaders).
accept('application/json').
send(reaction).
end(this.handleResponse.bind(this, 'saveReaction', success, error));
}
deleteReaction(channelId, reaction, success, error) {
request.
post(`${this.getChannelNeededRoute(channelId)}/posts/${reaction.post_id}/reactions/delete`).
set(this.defaultHeaders).
accept('application/json').
send(reaction).
end(this.handleResponse.bind(this, 'deleteReaction', success, error));
}
listReactions(channelId, postId, success, error) {
request.
get(`${this.getChannelNeededRoute(channelId)}/posts/${postId}/reactions`).
set(this.defaultHeaders).
type('application/json').
accept('application/json').
end(this.handleResponse.bind(this, 'listReactions', success, error));
}
webrtcToken(success, error) {
request.post(`${this.getWebrtcRoute()}/token`).
set(this.defaultHeaders).

Просмотреть файл

@@ -5,6 +5,7 @@ import $ from 'jquery';
import ReactDOM from 'react-dom';
import AppDispatcher from '../dispatcher/app_dispatcher.jsx';
import Client from 'client/web_client.jsx';
import EmojiStore from 'stores/emoji_store.jsx';
import UserStore from 'stores/user_store.jsx';
import PostDeletedModal from './post_deleted_modal.jsx';
import PostStore from 'stores/post_store.jsx';
@@ -17,6 +18,7 @@ import FilePreview from './file_preview.jsx';
import * as Utils from 'utils/utils.jsx';
import * as UserAgent from 'utils/user_agent.jsx';
import * as GlobalActions from 'actions/global_actions.jsx';
import * as PostActions from 'actions/post_actions.jsx';
import Constants from 'utils/constants.jsx';
@@ -25,6 +27,8 @@ import {FormattedMessage} from 'react-intl';
const ActionTypes = Constants.ActionTypes;
const KeyCodes = Constants.KeyCodes;
import {REACTION_PATTERN} from './create_post.jsx';
import React from 'react';
export default class CreateComment extends React.Component {
@@ -34,6 +38,8 @@ export default class CreateComment extends React.Component {
this.lastTime = 0;
this.handleSubmit = this.handleSubmit.bind(this);
this.handleSubmitPost = this.handleSubmitPost.bind(this);
this.handleSubmitReaction = this.handleSubmitReaction.bind(this);
this.commentMsgKeyPress = this.commentMsgKeyPress.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
@@ -100,15 +106,9 @@ export default class CreateComment extends React.Component {
return;
}
const post = {};
post.file_ids = [];
post.message = this.state.message;
const message = this.state.message;
if (post.message.trim().length === 0 && this.state.fileInfos.length === 0) {
return;
}
if (post.message.length > Constants.CHARACTER_LIMIT) {
if (message.length > Constants.CHARACTER_LIMIT) {
this.setState({
postError: (
<FormattedMessage
@@ -121,15 +121,43 @@ export default class CreateComment extends React.Component {
return;
}
MessageHistoryStore.storeMessageInHistory(this.state.message);
MessageHistoryStore.storeMessageInHistory(message);
if (message.trim().length === 0 && this.state.previews.length === 0) {
return;
}
const isReaction = REACTION_PATTERN.exec(message);
if (isReaction && EmojiStore.has(isReaction[2])) {
this.handleSubmitReaction(isReaction);
} else {
this.handleSubmitPost(message);
}
this.setState({
message: '',
submitting: false,
postError: null,
fileInfos: [],
serverError: null
});
const fasterThanHumanWillClick = 150;
const forceFocus = (Date.now() - this.state.lastBlurAt < fasterThanHumanWillClick);
this.focusTextbox(forceFocus);
}
handleSubmitPost(message) {
const userId = UserStore.getCurrentId();
const time = Utils.getTimestamp();
const post = {};
post.file_ids = [];
post.message = message;
post.channel_id = this.props.channelId;
post.root_id = this.props.rootId;
post.parent_id = this.props.rootId;
post.file_ids = this.state.fileInfos.map((info) => info.id);
const time = Utils.getTimestamp();
post.pending_post_id = `${userId}:${time}`;
post.user_id = userId;
post.create_at = time;
@@ -160,18 +188,21 @@ export default class CreateComment extends React.Component {
});
}
);
}
this.setState({
message: '',
submitting: false,
postError: null,
fileInfos: [],
serverError: null
});
handleSubmitReaction(isReaction) {
const action = isReaction[1];
const fasterThanHumanWillClick = 150;
const forceFocus = (Date.now() - this.state.lastBlurAt < fasterThanHumanWillClick);
this.focusTextbox(forceFocus);
const emojiName = isReaction[2];
const postId = this.props.latestPostId;
if (action === '+') {
PostActions.addReaction(this.props.channelId, postId, emojiName);
} else if (action === '-') {
PostActions.removeReaction(this.props.channelId, postId, emojiName);
}
PostStore.storeCommentDraft(this.props.rootId, null);
}
commentMsgKeyPress(e) {
@@ -455,5 +486,6 @@ export default class CreateComment extends React.Component {
CreateComment.propTypes = {
channelId: React.PropTypes.string.isRequired,
rootId: React.PropTypes.string.isRequired
rootId: React.PropTypes.string.isRequired,
latestPostId: React.PropTypes.string.isRequired
};

Просмотреть файл

@@ -9,14 +9,16 @@ import FilePreview from './file_preview.jsx';
import PostDeletedModal from './post_deleted_modal.jsx';
import TutorialTip from './tutorial/tutorial_tip.jsx';
import AppDispatcher from '../dispatcher/app_dispatcher.jsx';
import AppDispatcher from 'dispatcher/app_dispatcher.jsx';
import * as GlobalActions from 'actions/global_actions.jsx';
import Client from 'client/web_client.jsx';
import * as Utils from 'utils/utils.jsx';
import * as UserAgent from 'utils/user_agent.jsx';
import * as ChannelActions from 'actions/channel_actions.jsx';
import * as PostActions from 'actions/post_actions.jsx';
import ChannelStore from 'stores/channel_store.jsx';
import EmojiStore from 'stores/emoji_store.jsx';
import PostStore from 'stores/post_store.jsx';
import MessageHistoryStore from 'stores/message_history_store.jsx';
import UserStore from 'stores/user_store.jsx';
@@ -34,6 +36,8 @@ const KeyCodes = Constants.KeyCodes;
import React from 'react';
export const REACTION_PATTERN = /^(\+|-):([^:\s]+):\s*$/;
export default class CreatePost extends React.Component {
constructor(props) {
super(props);
@@ -101,6 +105,7 @@ export default class CreatePost extends React.Component {
this.setState({submitting: true, serverError: null});
const isReaction = REACTION_PATTERN.exec(post.message);
if (post.message.indexOf('/') === 0) {
PostStore.storeDraft(this.state.channelId, null);
this.setState({message: '', postError: null, fileInfos: []});
@@ -123,14 +128,18 @@ export default class CreatePost extends React.Component {
const state = {};
state.serverError = err.message;
state.submitting = false;
this.setState(state);
this.setState({state});
}
}
);
} else if (isReaction && EmojiStore.has(isReaction[2])) {
this.sendReaction(isReaction);
} else {
this.sendMessage(post);
}
this.setState({message: '', submitting: false, postError: null, fileInfos: [], serverError: null});
const fasterThanHumanWillClick = 150;
const forceFocus = (Date.now() - this.state.lastBlurAt < fasterThanHumanWillClick);
this.focusTextbox(forceFocus);
@@ -148,7 +157,6 @@ export default class CreatePost extends React.Component {
post.parent_id = this.state.parentId;
GlobalActions.emitUserPostedEvent(post);
this.setState({message: '', submitting: false, postError: null, fileInfos: [], serverError: null});
Client.createPost(post,
(data) => {
@@ -177,6 +185,21 @@ export default class CreatePost extends React.Component {
);
}
sendReaction(isReaction) {
const action = isReaction[1];
const emojiName = isReaction[2];
const postId = PostStore.getLatestPost(this.state.channelId).id;
if (action === '+') {
PostActions.addReaction(this.state.channelId, postId, emojiName);
} else if (action === '-') {
PostActions.removeReaction(this.state.channelId, postId, emojiName);
}
PostStore.storeCurrentDraft(null);
}
focusTextbox(keepFocus = false) {
if (keepFocus || !Utils.isMobile()) {
this.refs.textbox.focus();

Просмотреть файл

@@ -85,7 +85,7 @@ export default class AddEmoji extends React.Component {
});
return;
} else if (EmojiStore.getSystemEmojis().has(emoji.name)) {
} else if (EmojiStore.hasSystemEmoji(emoji.name)) {
this.setState({
saving: false,
error: (

Просмотреть файл

@@ -255,6 +255,7 @@ export default class Post extends React.Component {
/>
<PostBody
post={post}
currentUser={this.props.currentUser}
sameRoot={this.props.sameRoot}
parentPost={parentPost}
handleCommentClick={this.handleCommentClick}

Просмотреть файл

@@ -10,6 +10,7 @@ import FileAttachmentListContainer from 'components/file_attachment_list_contain
import PostBodyAdditionalContent from './post_body_additional_content.jsx';
import PostMessageContainer from './post_message_container.jsx';
import PendingPostOptions from './pending_post_options.jsx';
import ReactionListContainer from './reaction_list_container.jsx';
import {FormattedMessage} from 'react-intl';
@@ -202,6 +203,10 @@ export default class PostBody extends React.Component {
<div className={'post__body ' + mentionHighlightClass}>
{messageWithAdditionalContent}
{fileAttachmentHolder}
<ReactionListContainer
post={post}
currentUserId={this.props.currentUser.id}
/>
</div>
</div>
);
@@ -210,6 +215,7 @@ export default class PostBody extends React.Component {
PostBody.propTypes = {
post: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.object.isRequired,
parentPost: React.PropTypes.object,
retryPost: React.PropTypes.func,
handleCommentClick: React.PropTypes.func.isRequired,

Просмотреть файл

@@ -0,0 +1,136 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import React from 'react';
import EmojiStore from 'stores/emoji_store.jsx';
import * as PostActions from 'actions/post_actions.jsx';
import * as Utils from 'utils/utils.jsx';
import {FormattedHTMLMessage, FormattedMessage} from 'react-intl';
import {OverlayTrigger, Tooltip} from 'react-bootstrap';
export default class Reaction extends React.Component {
static propTypes = {
post: React.PropTypes.object.isRequired,
currentUserId: React.PropTypes.string.isRequired,
emojiName: React.PropTypes.string.isRequired,
reactions: React.PropTypes.arrayOf(React.PropTypes.object)
}
constructor(props) {
super(props);
this.addReaction = this.addReaction.bind(this);
this.removeReaction = this.removeReaction.bind(this);
}
addReaction(e) {
e.preventDefault();
PostActions.addReaction(this.props.post.channel_id, this.props.post.id, this.props.emojiName);
}
removeReaction(e) {
e.preventDefault();
PostActions.removeReaction(this.props.post.channel_id, this.props.post.id, this.props.emojiName);
}
render() {
if (!EmojiStore.has(this.props.emojiName)) {
return null;
}
let currentUserReacted = false;
const users = [];
for (const reaction of this.props.reactions) {
if (reaction.user_id === this.props.currentUserId) {
currentUserReacted = true;
} else {
users.push(Utils.displayUsername(reaction.user_id));
}
}
// sort users in alphabetical order with "you" being first if the current user reacted
users.sort();
if (currentUserReacted) {
users.unshift(Utils.localizeMessage('reaction.you', 'You'));
}
let tooltip;
if (users.length > 1) {
tooltip = (
<FormattedHTMLMessage
id='reaction.multipleReacted'
defaultMessage='<b>{users} and {lastUser}</b> reacted with <b>:{emojiName}:</b>'
values={{
users: users.slice(0, -1).join(', '),
lastUser: users[users.length - 1],
emojiName: this.props.emojiName
}}
/>
);
} else {
tooltip = (
<FormattedHTMLMessage
id='reaction.oneReacted'
defaultMessage='<b>{user}</b> reacted with <b>:{emojiName}:</b>'
values={{
user: users[0],
emojiName: this.props.emojiName
}}
/>
);
}
let handleClick;
let clickTooltip;
let className = 'post-reaction';
if (currentUserReacted) {
handleClick = this.removeReaction;
clickTooltip = (
<FormattedMessage
id='reaction.clickToRemove'
defaultMessage='(click to remove)'
/>
);
className += ' post-reaction--current-user';
} else {
handleClick = this.addReaction;
clickTooltip = (
<FormattedMessage
id='reaction.clickToAdd'
defaultMessage='(click to add)'
/>
);
}
return (
<OverlayTrigger
delayShow={1000}
placement='top'
shouldUpdatePosition={true}
overlay={
<Tooltip>
{tooltip}
<br/>
{clickTooltip}
</Tooltip>
}
>
<div
className={className}
onClick={handleClick}
>
<img
className='post-reaction__emoji'
src={EmojiStore.getEmojiImageUrl(EmojiStore.get(this.props.emojiName))}
/>
<span className='post-reaction__count'>
{this.props.reactions.length}
</span>
</div>
</OverlayTrigger>
);
}
}

Просмотреть файл

@@ -0,0 +1,82 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import React from 'react';
import * as AsyncClient from 'utils/async_client.jsx';
import ReactionStore from 'stores/reaction_store.jsx';
import ReactionListView from './reaction_list_view.jsx';
export default class ReactionListContainer extends React.Component {
static propTypes = {
post: React.PropTypes.object.isRequired,
currentUserId: React.PropTypes.string.isRequired
}
constructor(props) {
super(props);
this.handleReactionsChanged = this.handleReactionsChanged.bind(this);
this.state = {
reactions: ReactionStore.getReactions(this.props.post.id)
};
}
componentDidMount() {
ReactionStore.addChangeListener(this.props.post.id, this.handleReactionsChanged);
if (this.props.post.has_reactions) {
AsyncClient.listReactions(this.props.post.channel_id, this.props.post.id);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.post.id !== this.props.post.id) {
ReactionStore.removeChangeListener(this.props.post.id, this.handleReactionsChanged);
ReactionStore.addChangeListener(nextProps.post.id, this.handleReactionsChanged);
this.setState({
reactions: ReactionStore.getReactions(nextProps.post.id)
});
}
}
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.post.has_reactions !== this.props.post.has_reactions) {
return true;
}
if (nextState.reactions !== this.state.reactions) {
// this will only work so long as the entries in the ReactionStore are never mutated
return true;
}
return false;
}
componentWillUnmount() {
ReactionStore.removeChangeListener(this.props.post.id, this.handleReactionsChanged);
}
handleReactionsChanged() {
this.setState({
reactions: ReactionStore.getReactions(this.props.post.id)
});
}
render() {
if (!this.props.post.has_reactions) {
return null;
}
return (
<ReactionListView
post={this.props.post}
currentUserId={this.props.currentUserId}
reactions={this.state.reactions}
/>
);
}
}

Просмотреть файл

@@ -0,0 +1,48 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import React from 'react';
import Reaction from './reaction.jsx';
export default class ReactionListView extends React.Component {
static propTypes = {
post: React.PropTypes.object.isRequired,
currentUserId: React.PropTypes.string.isRequired,
reactions: React.PropTypes.arrayOf(React.PropTypes.object)
}
render() {
const reactionsByName = new Map();
const emojiNames = [];
for (const reaction of this.props.reactions) {
const emojiName = reaction.emoji_name;
if (reactionsByName.has(emojiName)) {
reactionsByName.get(emojiName).push(reaction);
} else {
emojiNames.push(emojiName);
reactionsByName.set(emojiName, [reaction]);
}
}
const children = emojiNames.map((emojiName) => {
return (
<Reaction
key={emojiName}
post={this.props.post}
currentUserId={this.props.currentUserId}
emojiName={emojiName}
reactions={reactionsByName.get(emojiName)}
/>
);
});
return (
<div className='post-reaction-list'>
{children}
</div>
);
}
}

Просмотреть файл

@@ -6,6 +6,7 @@ import FileAttachmentListContainer from './file_attachment_list_container.jsx';
import PendingPostOptions from 'components/post_view/components/pending_post_options.jsx';
import PostMessageContainer from 'components/post_view/components/post_message_container.jsx';
import ProfilePicture from 'components/profile_picture.jsx';
import ReactionListContainer from 'components/post_view/components/reaction_list_container.jsx';
import RhsDropdown from 'components/rhs_dropdown.jsx';
import TeamStore from 'stores/team_store.jsx';
@@ -404,6 +405,10 @@ export default class RhsComment extends React.Component {
{message}
</div>
{fileAttachment}
<ReactionListContainer
post={post}
currentUserId={this.props.currentUser.id}
/>
</div>
</div>
</div>

Просмотреть файл

@@ -6,6 +6,7 @@ import PostBodyAdditionalContent from 'components/post_view/components/post_body
import PostMessageContainer from 'components/post_view/components/post_message_container.jsx';
import FileAttachmentListContainer from './file_attachment_list_container.jsx';
import ProfilePicture from 'components/profile_picture.jsx';
import ReactionListContainer from 'components/post_view/components/reaction_list_container.jsx';
import RhsDropdown from 'components/rhs_dropdown.jsx';
import ChannelStore from 'stores/channel_store.jsx';
@@ -389,6 +390,10 @@ export default class RhsRootPost extends React.Component {
message={messageWrapper}
/>
{fileAttachment}
<ReactionListContainer
post={post}
currentUserId={this.props.currentUser.id}
/>
</div>
</div>
</div>

Просмотреть файл

@@ -339,6 +339,7 @@ export default class RhsThread extends React.Component {
<CreateComment
channelId={selected.channel_id}
rootId={selected.id}
latestPostId={postsArray.length > 0 ? postsArray[postsArray.length - 1].id : selected.id}
/>
</div>
</div>

Просмотреть файл

@@ -46,20 +46,23 @@ export default class EmoticonProvider {
handlePretextChanged(suggestionId, pretext) {
let hasSuggestions = false;
// look for partial matches among the named emojis
const captured = (/(?:^|\s)(:([^:\s]*))$/g).exec(pretext);
// look for the potential emoticons at the start of the text, after whitespace, and at the start of emoji reaction commands
const captured = (/(^|\s|^\+|^-)(:([^:\s]*))$/g).exec(pretext);
if (captured) {
const text = captured[1];
const partialName = captured[2];
const prefix = captured[1];
const text = captured[2];
const partialName = captured[3];
const matched = [];
// check for text emoticons
for (const emoticon of Object.keys(Emoticons.emoticonPatterns)) {
if (Emoticons.emoticonPatterns[emoticon].test(text)) {
SuggestionStore.addSuggestion(suggestionId, text, EmojiStore.get(emoticon), EmoticonSuggestion, text);
// check for text emoticons if this isn't for an emoji reaction
if (prefix !== '-' && prefix !== '+') {
for (const emoticon of Object.keys(Emoticons.emoticonPatterns)) {
if (Emoticons.emoticonPatterns[emoticon].test(text)) {
SuggestionStore.addSuggestion(suggestionId, text, EmojiStore.get(emoticon), EmoticonSuggestion, text);
hasSuggestions = true;
hasSuggestions = true;
}
}
}
@@ -76,11 +79,14 @@ export default class EmoticonProvider {
// sort the emoticons so that emoticons starting with the entered text come first
matched.sort((a, b) => {
const aPrefix = a.name.startsWith(partialName);
const bPrefix = b.name.startsWith(partialName);
const aName = a.name || a.aliases[0];
const bName = b.name || b.aliases[0];
const aPrefix = aName.startsWith(partialName);
const bPrefix = bName.startsWith(partialName);
if (aPrefix === bPrefix) {
return a.name.localeCompare(b.name);
return aName.localeCompare(bName);
} else if (aPrefix) {
return -1;
}
@@ -88,7 +94,7 @@ export default class EmoticonProvider {
return 1;
});
const terms = matched.map((emoticon) => ':' + emoticon.name + ':');
const terms = matched.map((emoticon) => ':' + (emoticon.name || emoticon.aliases[0]) + ':');
SuggestionStore.clearSuggestions(suggestionId);
if (terms.length > 0) {

Просмотреть файл

@@ -26,7 +26,6 @@ export default class Textbox extends React.Component {
this.focus = this.focus.bind(this);
this.recalculateSize = this.recalculateSize.bind(this);
this.getStateFromStores = this.getStateFromStores.bind(this);
this.onRecievedError = this.onRecievedError.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
@@ -48,16 +47,6 @@ export default class Textbox extends React.Component {
}
}
getStateFromStores() {
const error = ErrorStore.getLastError();
if (error) {
return {message: error.message};
}
return {message: null};
}
componentDidMount() {
ErrorStore.addChangeListener(this.onRecievedError);
}

Просмотреть файл

@@ -1620,6 +1620,11 @@
"post_info.reply": "Reply",
"posts_view.loadMore": "Load more messages",
"posts_view.newMsg": "New Messages",
"reaction.clickToAdd": "(click to add)",
"reaction.clickToRemove": "(click to remove)",
"reaction.multipleReacted": "<b>{users} and {lastUser}</b> reacted with <b>:{emojiName}:</b>",
"reaction.oneReacted": "<b>{user}</b> reacted with <b>:{emojiName}:</b>",
"reaction.you": "You",
"removed_channel.channelName": "the channel",
"removed_channel.from": "Removed from ",
"removed_channel.okay": "Okay",

Двоичные данные
webapp/images/emoji/basecamp.png

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 898 B

Двоичные данные
webapp/images/emoji/basecampy.png

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 2.9 KiB

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 6.4 KiB

После

Ширина:  |  Высота:  |  Размер: 6.4 KiB

Просмотреть файл

@@ -1206,3 +1206,31 @@
margin-left: 50px !important;
min-width: 320px;
}
.post-reaction-list {
height: 24px;
}
.post-reaction {
border: 1px solid $primary-color;
border-radius: 3px;
cursor: pointer;
display: inline-block;
padding: 1px 2px;
@include user-select(none);
.post-reaction__emoji {
height: 14px;
margin-top: 3px;
width: 14px;
vertical-align: top;
}
& + & {
margin-left: 5px;
}
&--current-user {
// background-colour set by theme code
}
}

Просмотреть файл

@@ -5,12 +5,64 @@ import AppDispatcher from '../dispatcher/app_dispatcher.jsx';
import Constants from 'utils/constants.jsx';
import EventEmitter from 'events';
import EmojiJson from 'utils/emoji.json';
import * as Emoji from 'utils/emoji.jsx';
const ActionTypes = Constants.ActionTypes;
const CHANGE_EVENT = 'changed';
// Wrap the contents of the store so that we don't need to construct an ES6 map where most of the content
// (the system emojis) will never change. It provides the get/has functions of a map and an iterator so
// that it can be used in for..of loops
class EmojiMap {
constructor(customEmojis) {
this.customEmojis = customEmojis;
// Store customEmojis to an array so we can iterate it more easily
this.customEmojisArray = [...customEmojis];
}
has(name) {
return Emoji.EmojiIndicesByAlias.has(name) || this.customEmojis.has(name);
}
get(name) {
if (Emoji.EmojiIndicesByAlias.has(name)) {
return Emoji.Emojis[Emoji.EmojiIndicesByAlias.get(name)];
}
return this.customEmojis.get(name);
}
[Symbol.iterator]() {
const customEmojisArray = this.customEmojisArray;
return {
systemIndex: 0,
customIndex: 0,
next() {
if (this.systemIndex < Emoji.Emojis.length) {
const emoji = Emoji.Emojis[this.systemIndex];
this.systemIndex += 1;
return {value: [emoji.aliases[0], emoji]};
}
if (this.customIndex < customEmojisArray.length) {
const emoji = customEmojisArray[this.customIndex][1];
this.customIndex += 1;
return {value: [emoji.name, emoji]};
}
return {done: true};
}
};
}
}
class EmojiStore extends EventEmitter {
constructor() {
super();
@@ -19,18 +71,10 @@ class EmojiStore extends EventEmitter {
this.setMaxListeners(600);
this.emojis = new Map(EmojiJson);
this.systemEmojis = new Map(EmojiJson);
this.unicodeEmojis = new Map();
for (const [, emoji] of this.systemEmojis) {
if (emoji.unicode) {
this.unicodeEmojis.set(emoji.unicode, emoji);
}
}
this.receivedCustomEmojis = false;
this.customEmojis = new Map();
this.map = new EmojiMap(this.customEmojis);
}
addChangeListener(callback) {
@@ -50,20 +94,19 @@ class EmojiStore extends EventEmitter {
}
setCustomEmojis(customEmojis) {
customEmojis.sort((a, b) => a.name[0].localeCompare(b.name[0]));
this.customEmojis = new Map();
for (const emoji of customEmojis) {
this.addCustomEmoji(emoji);
}
this.sortCustomEmojis();
this.updateEmojiMap();
this.map = new EmojiMap(this.customEmojis);
}
addCustomEmoji(emoji) {
this.customEmojis.set(emoji.name, emoji);
// this doesn't update this.emojis, but it's only called by setCustomEmojis which does that afterwards
}
removeCustomEmoji(id) {
@@ -73,21 +116,10 @@ class EmojiStore extends EventEmitter {
break;
}
}
this.updateEmojiMap();
}
sortCustomEmojis() {
this.customEmojis = new Map([...this.customEmojis.entries()].sort((a, b) => a[0].localeCompare(b[0])));
}
updateEmojiMap() {
// add custom emojis to the map first so that they can't override system ones
this.emojis = new Map([...this.customEmojis, ...this.systemEmojis]);
}
getSystemEmojis() {
return this.systemEmojis;
hasSystemEmoji(name) {
return Emoji.EmojiIndicesByAlias.has(name);
}
getCustomEmojiMap() {
@@ -95,24 +127,23 @@ class EmojiStore extends EventEmitter {
}
getEmojis() {
return this.emojis;
return this.map;
}
has(name) {
return this.emojis.has(name);
return this.map.has(name);
}
get(name) {
// prioritize system emojis so that custom ones can't override them
return this.emojis.get(name);
return this.map.get(name);
}
hasUnicode(codepoint) {
return this.unicodeEmojis.has(codepoint);
return Emoji.EmojiIndicesByUnicode.has(codepoint);
}
getUnicode(codepoint) {
return this.unicodeEmojis.get(codepoint);
return Emoji.Emojis[Emoji.EmojiIndicesByUnicode.get(codepoint)];
}
getEmojiImageUrl(emoji) {
@@ -121,7 +152,7 @@ class EmojiStore extends EventEmitter {
return `/api/v3/emoji/${emoji.id}`;
}
const filename = emoji.unicode || emoji.filename || emoji.name;
const filename = emoji.filename || emoji.aliases[0];
return Constants.EMOJI_PATH + '/' + filename + '.png';
}

Просмотреть файл

@@ -118,7 +118,15 @@ class PostStoreClass extends EventEmitter {
getEarliestPost(id) {
if (this.postsInfo.hasOwnProperty(id)) {
return this.postsInfo[id].postList.posts[this.postsInfo[id].postList.order[this.postsInfo[id].postList.order.length - 1]];
const postList = this.postsInfo[id].postList;
for (let i = postList.order.length - 1; i >= 0; i--) {
const postId = postList.order[i];
if (postList.posts[postId].state !== Constants.POST_DELETED) {
return postList.posts[postId];
}
}
}
return null;
@@ -126,7 +134,13 @@ class PostStoreClass extends EventEmitter {
getLatestPost(id) {
if (this.postsInfo.hasOwnProperty(id)) {
return this.postsInfo[id].postList.posts[this.postsInfo[id].postList.order[0]];
const postList = this.postsInfo[id].postList;
for (const postId of postList.order) {
if (postList.posts[postId].state !== Constants.POST_DELETED) {
return postList.posts[postId];
}
}
}
return null;
@@ -318,7 +332,8 @@ class PostStoreClass extends EventEmitter {
// make sure to copy the post so that component state changes work properly
postList.posts[post.id] = Object.assign({}, post, {
state: Constants.POST_DELETED,
file_ids: []
file_ids: [],
has_reactions: false
});
}
}

92
webapp/stores/reaction_store.jsx Обычный файл
Просмотреть файл

@@ -0,0 +1,92 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import AppDispatcher from '../dispatcher/app_dispatcher.jsx';
import Constants from 'utils/constants.jsx';
import EventEmitter from 'events';
const ActionTypes = Constants.ActionTypes;
const CHANGE_EVENT = 'changed';
class ReactionStore extends EventEmitter {
constructor() {
super();
this.dispatchToken = AppDispatcher.register(this.handleEventPayload.bind(this));
this.reactions = new Map();
this.setMaxListeners(600);
}
addChangeListener(postId, callback) {
this.on(CHANGE_EVENT + postId, callback);
}
removeChangeListener(postId, callback) {
this.removeListener(CHANGE_EVENT + postId, callback);
}
emitChange(postId) {
this.emit(CHANGE_EVENT + postId, postId);
}
setReactions(postId, reactions) {
this.reactions.set(postId, reactions);
}
addReaction(postId, reaction) {
const reactions = [];
for (const existing of this.getReactions(postId)) {
// make sure not to add duplicates
if (existing.user_id !== reaction.user_id || existing.post_id !== reaction.post_id ||
existing.emoji_name !== reaction.emoji_name) {
reactions.push(existing);
}
}
reactions.push(reaction);
this.setReactions(postId, reactions);
}
removeReaction(postId, reaction) {
const reactions = [];
for (const existing of this.getReactions(postId)) {
if (existing.user_id !== reaction.user_id || existing.post_id !== reaction.post_id ||
existing.emoji_name !== reaction.emoji_name) {
reactions.push(existing);
}
}
this.setReactions(postId, reactions);
}
getReactions(postId) {
return this.reactions.get(postId) || [];
}
handleEventPayload(payload) {
const action = payload.action;
switch (action.type) {
case ActionTypes.RECEIVED_REACTIONS:
this.setReactions(action.postId, action.reactions);
this.emitChange(action.postId);
break;
case ActionTypes.ADDED_REACTION:
this.addReaction(action.postId, action.reaction);
this.emitChange(action.postId);
break;
case ActionTypes.REMOVED_REACTION:
this.removeReaction(action.postId, action.reaction);
this.emitChange(action.postId);
break;
}
}
}
export default new ReactionStore();

81
webapp/tests/client_reaction.test.jsx Обычный файл
Просмотреть файл

@@ -0,0 +1,81 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import TestHelper from './test_helper.jsx';
describe('Client.Reaction', function() {
this.timeout(100000);
it('saveListReaction', function(done) {
TestHelper.initBasic(() => {
const channelId = TestHelper.basicChannel().id;
const postId = TestHelper.basicPost().id;
const reaction = {
post_id: postId,
user_id: TestHelper.basicUser().id,
emoji_name: 'upside_down_face'
};
TestHelper.basicClient().saveReaction(
channelId,
reaction,
function() {
TestHelper.basicClient().listReactions(
channelId,
postId,
function(reactions) {
if (reactions.length === 1 &&
reactions[0].post_id === reaction.post_id &&
reactions[0].user_id === reaction.user_id &&
reactions[0].emoji_name === reaction.emoji_name) {
done();
} else {
done(new Error('test reaction wasn\'t returned'));
}
},
function(err) {
done(new Error(err.message));
}
);
},
function(err) {
done(new Error(err.message));
}
);
});
});
it('deleteReaction', function(done) {
TestHelper.initBasic(() => {
const channelId = TestHelper.basicChannel().id;
const postId = TestHelper.basicPost().id;
const reaction = {
post_id: postId,
user_id: TestHelper.basicUser().id,
emoji_name: 'upside_down_face'
};
TestHelper.basicClient().saveReaction(
channelId,
reaction,
function() {
TestHelper.basicClient().deleteReaction(
channelId,
reaction,
function() {
done();
},
function(err) {
done(new Error(err.message));
}
);
},
function(err) {
done(new Error(err.message));
}
);
});
});
});

Просмотреть файл

@@ -1527,3 +1527,53 @@ export function deleteEmoji(id) {
}
);
}
export function saveReaction(channelId, reaction) {
Client.saveReaction(
channelId,
reaction,
null, // the added reaction will be sent over the websocket
(err) => {
dispatchError(err, 'saveReaction');
}
);
}
export function deleteReaction(channelId, reaction) {
Client.deleteReaction(
channelId,
reaction,
null, // the removed reaction will be sent over the websocket
(err) => {
dispatchError(err, 'deleteReaction');
}
);
}
export function listReactions(channelId, postId) {
const callName = 'deleteEmoji' + postId;
if (isCallInProgress(callName)) {
return;
}
callTracker[callName] = utils.getTimestamp();
Client.listReactions(
channelId,
postId,
(data) => {
callTracker[callName] = 0;
AppDispatcher.handleServerAction({
type: ActionTypes.RECEIVED_REACTIONS,
postId,
reactions: data
});
},
(err) => {
callTracker[callName] = 0;
dispatchError(err, 'listReactions');
}
);
}

Просмотреть файл

@@ -122,6 +122,10 @@ export const ActionTypes = keyMirror({
UPDATED_CUSTOM_EMOJI: null,
REMOVED_CUSTOM_EMOJI: null,
RECEIVED_REACTIONS: null,
ADDED_REACTION: null,
REMOVED_REACTION: null,
RECEIVED_MSG: null,
RECEIVED_MY_TEAM: null,
@@ -206,7 +210,9 @@ export const SocketEvents = {
EPHEMERAL_MESSAGE: 'ephemeral_message',
STATUS_CHANGED: 'status_change',
HELLO: 'hello',
WEBRTC: 'webrtc'
WEBRTC: 'webrtc',
REACTION_ADDED: 'reaction_added',
REACTION_REMOVED: 'reaction_removed'
};
export const TutorialSteps = {

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

18
webapp/utils/emoji.jsx Обычный файл

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Просмотреть файл

@@ -539,6 +539,7 @@ export function applyTheme(theme) {
if (theme.mentionColor) {
changeCss('.sidebar--left .nav-pills__unread-indicator', 'color:' + theme.mentionColor);
changeCss('.sidebar--left .badge', 'color:' + theme.mentionColor + '!important;');
changeCss('.app__body .post-reaction--current-user', 'background-color:' + changeOpacity(theme.mentionColor, 0.4));
}
if (theme.centerChannelBg) {
@@ -628,6 +629,8 @@ export function applyTheme(theme) {
changeCss('.app__body .post.post--comment.current--user .post__body', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.2));
changeCss('.app__body .channel-header__info .status .offline--icon', 'fill:' + theme.centerChannelColor);
changeCss('.app__body .navbar .status .offline--icon', 'fill:' + theme.centerChannelColor);
changeCss('.app__body .post-reaction:not(.post-reaction--current-user)', 'background-color:' + changeOpacity(theme.centerChannelColor, 0.2));
changeCss('.app__body .post-reaction', 'border-color:' + theme.centerChannelColor);
}
if (theme.newMessageSeparator) {