Browse Source

chat fixes and optimizations (#431)

* - format messages on didMount instead of didUpdate. will also prevent bad setSTate loops when message is blank;
- convert message.js to functional comp
- prevent extra rerenders in messages and chat with shouldComponentUpdate checks

* revert chat test

* more concise returns;
pull/435/head
gingervitis 5 years ago committed by GitHub
parent
commit
0062896b7d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 33
      webroot/js/components/chat/chat-message-view.js
  2. 38
      webroot/js/components/chat/chat.js
  3. 41
      webroot/js/components/chat/message.js

33
webroot/js/components/chat/chat-message-view.js

@ -11,26 +11,39 @@ import { convertToText } from '../../utils/chat.js';
import { SOCKET_MESSAGE_TYPES } from '../../utils/websocket.js'; import { SOCKET_MESSAGE_TYPES } from '../../utils/websocket.js';
export default class ChatMessageView extends Component { export default class ChatMessageView extends Component {
async componentDidUpdate(prevProps) { constructor(props) {
super(props);
this.state = {
formattedMessage: '',
};
}
shouldComponentUpdate(nextProps, nextState) {
const { formattedMessage } = this.state;
const { formattedMessage: nextFormattedMessage } = nextState;
return (formattedMessage !== nextFormattedMessage);
}
async componentDidMount() {
const { message, username } = this.props; const { message, username } = this.props;
if (prevProps.message === message && this.state.formattedMessage) { if (message && username) {
return; const { body } = message;
const formattedMessage = await formatMessageText(body, username);
this.setState({
formattedMessage,
});
} }
const { body } = message; }
const formattedMessage = await formatMessageText(body, username);
this.setState({
formattedMessage
});
}
render() { render() {
const { message } = this.props; const { message } = this.props;
const { author, timestamp } = message; const { author, timestamp } = message;
const { formattedMessage } = this.state; const { formattedMessage } = this.state;
if (!formattedMessage) { if (!formattedMessage) {
return; return null;
} }
const formattedTimestamp = formatTimestamp(timestamp); const formattedTimestamp = formatTimestamp(timestamp);

38
webroot/js/components/chat/chat.js

@ -19,6 +19,7 @@ export default class Chat extends Component {
webSocketConnected: true, webSocketConnected: true,
messages: [], messages: [],
chatUserNames: [], chatUserNames: [],
newMessagesReceived: false,
}; };
this.scrollableMessagesContainer = createRef(); this.scrollableMessagesContainer = createRef();
@ -34,19 +35,37 @@ export default class Chat extends Component {
this.submitChat = this.submitChat.bind(this); this.submitChat = this.submitChat.bind(this);
this.scrollToBottom = this.scrollToBottom.bind(this); this.scrollToBottom = this.scrollToBottom.bind(this);
this.handleWindowResize = debounce(this.handleWindowResize.bind(this), 500); this.handleWindowResize = debounce(this.handleWindowResize.bind(this), 500);
this.handleNetworkingError = this.handleNetworkingError.bind(this);
this.messageListCallback = this.messageListCallback.bind(this); this.messageListCallback = this.messageListCallback.bind(this);
} }
componentDidMount() { componentDidMount() {
this.setupWebSocketCallbacks(); this.setupWebSocketCallbacks();
this.getChatHistory(); this.getChatHistory();
window.addEventListener('resize', this.handleWindowResize); window.addEventListener('resize', this.handleWindowResize);
this.messageListObserver = new MutationObserver(this.messageListCallback); this.messageListObserver = new MutationObserver(this.messageListCallback);
this.messageListObserver.observe(this.scrollableMessagesContainer.current, { childList: true }); this.messageListObserver.observe(this.scrollableMessagesContainer.current, { childList: true });
} }
shouldComponentUpdate(nextProps, nextState) {
const { username, chatInputEnabled } = this.props;
const { username: nextUserName, chatInputEnabled: nextChatEnabled } = nextProps;
const { webSocketConnected, messages, chatUserNames, newMessagesReceived } = this.state;
const {webSocketConnected: nextSocket, messages: nextMessages, chatUserNames: nextUserNames, newMessagesReceived: nextMessagesReceived } = nextState;
return (
username !== nextUserName ||
chatInputEnabled !== nextChatEnabled ||
webSocketConnected !== nextSocket ||
messages.length !== nextMessages.length ||
chatUserNames.length !== nextUserNames.length || newMessagesReceived !== nextMessagesReceived
);
}
componentDidUpdate(prevProps, prevState) { componentDidUpdate(prevProps, prevState) {
const { username: prevName } = prevProps; const { username: prevName } = prevProps;
const { username } = this.props; const { username } = this.props;
@ -61,7 +80,9 @@ export default class Chat extends Component {
// scroll to bottom of messages list when new ones come in // scroll to bottom of messages list when new ones come in
if (messages.length > prevMessages.length) { if (messages.length > prevMessages.length) {
this.newMessagesReceived = true; this.setState({
newMessagesReceived: true,
});
} }
} }
componentWillUnmount() { componentWillUnmount() {
@ -96,7 +117,7 @@ export default class Chat extends Component {
}); });
}) })
.catch(error => { .catch(error => {
// this.handleNetworkingError(`Fetch getChatHistory: ${error}`); this.handleNetworkingError(`Fetch getChatHistory: ${error}`);
}); });
} }
@ -113,6 +134,11 @@ export default class Chat extends Component {
this.addMessage(message); this.addMessage(message);
} }
handleNetworkingError(error) {
// todo: something more useful
console.log(error);
}
addMessage(message) { addMessage(message) {
const { messages: curMessages } = this.state; const { messages: curMessages } = this.state;
@ -196,14 +222,16 @@ export default class Chat extends Component {
if (numMutations) { if (numMutations) {
const item = mutations[numMutations - 1]; const item = mutations[numMutations - 1];
if (item.type === 'childList' && item.addedNodes.length) { if (item.type === 'childList' && item.addedNodes.length) {
if (this.newMessagesReceived) { if (this.state.newMessagesReceived) {
if (!this.receivedFirstMessages) { if (!this.receivedFirstMessages) {
this.scrollToBottom(); this.scrollToBottom();
this.receivedFirstMessages = true; this.receivedFirstMessages = true;
} else if (this.checkShouldScroll()) { } else if (this.checkShouldScroll()) {
this.scrollToBottom(); this.scrollToBottom();
} }
this.newMessagesReceived = false; this.setState({
newMessagesReceived: false,
});
} }
} }
} }

41
webroot/js/components/chat/message.js

@ -1,34 +1,31 @@
import { h, Component } from '/js/web_modules/preact.js'; import { h } from '/js/web_modules/preact.js';
import htm from '/js/web_modules/htm.js'; import htm from '/js/web_modules/htm.js';
const html = htm.bind(h); const html = htm.bind(h);
import ChatMessageView from './chat-message-view.js'; import ChatMessageView from './chat-message-view.js';
import { messageBubbleColorForString } from '../../utils/user-colors.js';
import { SOCKET_MESSAGE_TYPES } from '../../utils/websocket.js'; import { SOCKET_MESSAGE_TYPES } from '../../utils/websocket.js';
export default class Message extends Component { export default function Message(props) {
render(props) { const { message } = props;
const { message } = props; const { type } = message;
const { type } = message; if (type === SOCKET_MESSAGE_TYPES.CHAT || type === SOCKET_MESSAGE_TYPES.SYSTEM) {
if (type === SOCKET_MESSAGE_TYPES.CHAT || type === SOCKET_MESSAGE_TYPES.SYSTEM) { return html`<${ChatMessageView} ...${props} />`;
return html`<${ChatMessageView} ...${props} />`; } else if (type === SOCKET_MESSAGE_TYPES.NAME_CHANGE) {
} else if (type === SOCKET_MESSAGE_TYPES.NAME_CHANGE) { const { oldName, newName } = message;
const { oldName, newName } = message; return (
return ( html`
html` <div class="message message-name-change flex items-center justify-start p-3">
<div class="message message-name-change flex items-center justify-start p-3"> <div class="message-content flex flex-row items-center justify-center text-sm w-full">
<div class="message-content flex flex-row items-center justify-center text-sm w-full"> <div class="text-white text-center opacity-50 overflow-hidden break-words">
<div class="text-white text-center opacity-50 overflow-hidden break-words"> <span class="font-bold">${oldName}</span> is now known as <span class="font-bold">${newName}</span>.
<span class="font-bold">${oldName}</span> is now known as <span class="font-bold">${newName}</span>.
</div>
</div> </div>
</div> </div>
` </div>
); `
} else { );
console.log("Unknown message type:", type); } else {
} console.log("Unknown message type:", type);
} }
} }

Loading…
Cancel
Save