Prettified Code!
This commit is contained in:
@@ -5,9 +5,17 @@ const html = htm.bind(h);
|
|||||||
import Message from './message.js';
|
import Message from './message.js';
|
||||||
import ChatInput from './chat-input.js';
|
import ChatInput from './chat-input.js';
|
||||||
import { CALLBACKS, SOCKET_MESSAGE_TYPES } from '../../utils/websocket.js';
|
import { CALLBACKS, SOCKET_MESSAGE_TYPES } from '../../utils/websocket.js';
|
||||||
import { jumpToBottom, debounce, getLocalStorage } from '../../utils/helpers.js';
|
import {
|
||||||
|
jumpToBottom,
|
||||||
|
debounce,
|
||||||
|
getLocalStorage,
|
||||||
|
} from '../../utils/helpers.js';
|
||||||
import { extraUserNamesFromMessageHistory } from '../../utils/chat.js';
|
import { extraUserNamesFromMessageHistory } from '../../utils/chat.js';
|
||||||
import { URL_CHAT_HISTORY, MESSAGE_JUMPTOBOTTOM_BUFFER, KEY_CUSTOM_USERNAME_SET } from '../../utils/constants.js';
|
import {
|
||||||
|
URL_CHAT_HISTORY,
|
||||||
|
MESSAGE_JUMPTOBOTTOM_BUFFER,
|
||||||
|
KEY_CUSTOM_USERNAME_SET,
|
||||||
|
} from '../../utils/constants.js';
|
||||||
|
|
||||||
export default class Chat extends Component {
|
export default class Chat extends Component {
|
||||||
constructor(props, context) {
|
constructor(props, context) {
|
||||||
@@ -43,37 +51,46 @@ export default class Chat extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
this.setupWebSocketCallbacks();
|
this.setupWebSocketCallbacks();
|
||||||
this.getChatHistory();
|
this.getChatHistory();
|
||||||
|
|
||||||
window.addEventListener('resize', this.handleWindowResize);
|
window.addEventListener('resize', this.handleWindowResize);
|
||||||
|
|
||||||
if (!this.props.messagesOnly) {
|
if (!this.props.messagesOnly) {
|
||||||
window.addEventListener('blur', this.handleWindowBlur);
|
window.addEventListener('blur', this.handleWindowBlur);
|
||||||
window.addEventListener('focus', this.handleWindowFocus);
|
window.addEventListener('focus', this.handleWindowFocus);
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
shouldComponentUpdate(nextProps, nextState) {
|
||||||
const { username, chatInputEnabled } = this.props;
|
const { username, chatInputEnabled } = this.props;
|
||||||
const { username: nextUserName, chatInputEnabled: nextChatEnabled } = nextProps;
|
const { username: nextUserName, chatInputEnabled: nextChatEnabled } =
|
||||||
|
nextProps;
|
||||||
|
|
||||||
const { webSocketConnected, messages, chatUserNames, newMessagesReceived } = this.state;
|
const { webSocketConnected, messages, chatUserNames, newMessagesReceived } =
|
||||||
const {webSocketConnected: nextSocket, messages: nextMessages, chatUserNames: nextUserNames, newMessagesReceived: nextMessagesReceived } = nextState;
|
this.state;
|
||||||
|
const {
|
||||||
|
webSocketConnected: nextSocket,
|
||||||
|
messages: nextMessages,
|
||||||
|
chatUserNames: nextUserNames,
|
||||||
|
newMessagesReceived: nextMessagesReceived,
|
||||||
|
} = nextState;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
username !== nextUserName ||
|
username !== nextUserName ||
|
||||||
chatInputEnabled !== nextChatEnabled ||
|
chatInputEnabled !== nextChatEnabled ||
|
||||||
webSocketConnected !== nextSocket ||
|
webSocketConnected !== nextSocket ||
|
||||||
messages.length !== nextMessages.length ||
|
messages.length !== nextMessages.length ||
|
||||||
chatUserNames.length !== nextUserNames.length || newMessagesReceived !== nextMessagesReceived
|
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;
|
||||||
@@ -98,50 +115,59 @@ export default class Chat extends Component {
|
|||||||
if (!this.props.messagesOnly) {
|
if (!this.props.messagesOnly) {
|
||||||
window.removeEventListener('blur', this.handleWindowBlur);
|
window.removeEventListener('blur', this.handleWindowBlur);
|
||||||
window.removeEventListener('focus', this.handleWindowFocus);
|
window.removeEventListener('focus', this.handleWindowFocus);
|
||||||
}
|
}
|
||||||
this.messageListObserver.disconnect();
|
this.messageListObserver.disconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
setupWebSocketCallbacks() {
|
setupWebSocketCallbacks() {
|
||||||
this.websocket = this.props.websocket;
|
this.websocket = this.props.websocket;
|
||||||
if (this.websocket) {
|
if (this.websocket) {
|
||||||
this.websocket.addListener(CALLBACKS.RAW_WEBSOCKET_MESSAGE_RECEIVED, this.receivedWebsocketMessage);
|
this.websocket.addListener(
|
||||||
this.websocket.addListener(CALLBACKS.WEBSOCKET_CONNECTED, this.websocketConnected);
|
CALLBACKS.RAW_WEBSOCKET_MESSAGE_RECEIVED,
|
||||||
this.websocket.addListener(CALLBACKS.WEBSOCKET_DISCONNECTED, this.websocketDisconnected);
|
this.receivedWebsocketMessage
|
||||||
|
);
|
||||||
|
this.websocket.addListener(
|
||||||
|
CALLBACKS.WEBSOCKET_CONNECTED,
|
||||||
|
this.websocketConnected
|
||||||
|
);
|
||||||
|
this.websocket.addListener(
|
||||||
|
CALLBACKS.WEBSOCKET_DISCONNECTED,
|
||||||
|
this.websocketDisconnected
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// fetch chat history
|
// fetch chat history
|
||||||
getChatHistory() {
|
getChatHistory() {
|
||||||
fetch(URL_CHAT_HISTORY)
|
fetch(URL_CHAT_HISTORY)
|
||||||
.then(response => {
|
.then((response) => {
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`Network response was not ok ${response.ok}`);
|
throw new Error(`Network response was not ok ${response.ok}`);
|
||||||
}
|
}
|
||||||
return response.json();
|
return response.json();
|
||||||
})
|
})
|
||||||
.then(data => {
|
.then((data) => {
|
||||||
// extra user names
|
// extra user names
|
||||||
const chatUserNames = extraUserNamesFromMessageHistory(data);
|
const chatUserNames = extraUserNamesFromMessageHistory(data);
|
||||||
this.setState({
|
this.setState({
|
||||||
messages: this.state.messages.concat(data),
|
messages: this.state.messages.concat(data),
|
||||||
chatUserNames,
|
chatUserNames,
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
this.handleNetworkingError(`Fetch getChatHistory: ${error}`);
|
||||||
});
|
});
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
this.handleNetworkingError(`Fetch getChatHistory: ${error}`);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sendUsernameChange(oldName, newName) {
|
sendUsernameChange(oldName, newName) {
|
||||||
clearTimeout(this.sendUserJoinedEvent);
|
clearTimeout(this.sendUserJoinedEvent);
|
||||||
|
|
||||||
const nameChange = {
|
const nameChange = {
|
||||||
type: SOCKET_MESSAGE_TYPES.NAME_CHANGE,
|
type: SOCKET_MESSAGE_TYPES.NAME_CHANGE,
|
||||||
oldName,
|
oldName,
|
||||||
newName,
|
newName,
|
||||||
};
|
};
|
||||||
this.websocket.send(nameChange);
|
this.websocket.send(nameChange);
|
||||||
}
|
}
|
||||||
|
|
||||||
receivedWebsocketMessage(message) {
|
receivedWebsocketMessage(message) {
|
||||||
@@ -164,7 +190,9 @@ export default class Chat extends Component {
|
|||||||
const { messages: curMessages } = this.state;
|
const { messages: curMessages } = this.state;
|
||||||
const { messagesOnly } = this.props;
|
const { messagesOnly } = this.props;
|
||||||
|
|
||||||
const existingIndex = curMessages.findIndex(item => item.id === messageId);
|
const existingIndex = curMessages.findIndex(
|
||||||
|
(item) => item.id === messageId
|
||||||
|
);
|
||||||
|
|
||||||
// If the message already exists and this is an update event
|
// If the message already exists and this is an update event
|
||||||
// then update it.
|
// then update it.
|
||||||
@@ -177,16 +205,20 @@ export default class Chat extends Component {
|
|||||||
// if message exists and should now hide, take it out.
|
// if message exists and should now hide, take it out.
|
||||||
if (existingIndex >= 0 && !messageVisible) {
|
if (existingIndex >= 0 && !messageVisible) {
|
||||||
this.setState({
|
this.setState({
|
||||||
messages: curMessages.filter(item => item.id !== messageId),
|
messages: curMessages.filter((item) => item.id !== messageId),
|
||||||
});
|
});
|
||||||
} else if (existingIndex === -1 && messageVisible) {
|
} else if (existingIndex === -1 && messageVisible) {
|
||||||
// insert message at timestamp
|
// insert message at timestamp
|
||||||
const insertAtIndex = curMessages.findIndex((item, index) => {
|
const insertAtIndex = curMessages.findIndex((item, index) => {
|
||||||
const time = item.timestamp || messageTimestamp;
|
const time = item.timestamp || messageTimestamp;
|
||||||
const nextMessage = index < curMessages.length - 1 && curMessages[index + 1];
|
const nextMessage =
|
||||||
|
index < curMessages.length - 1 && curMessages[index + 1];
|
||||||
const nextTime = nextMessage.timestamp || messageTimestamp;
|
const nextTime = nextMessage.timestamp || messageTimestamp;
|
||||||
const messageTimestampDate = new Date(messageTimestamp);
|
const messageTimestampDate = new Date(messageTimestamp);
|
||||||
return messageTimestampDate > (new Date(time)) && messageTimestampDate <= (new Date(nextTime));
|
return (
|
||||||
|
messageTimestampDate > new Date(time) &&
|
||||||
|
messageTimestampDate <= new Date(nextTime)
|
||||||
|
);
|
||||||
});
|
});
|
||||||
updatedMessageList.splice(insertAtIndex + 1, 0, convertedMessage);
|
updatedMessageList.splice(insertAtIndex + 1, 0, convertedMessage);
|
||||||
this.setState({
|
this.setState({
|
||||||
@@ -216,7 +248,9 @@ export default class Chat extends Component {
|
|||||||
webSocketConnected: true,
|
webSocketConnected: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const hasPreviouslySetCustomUsername = getLocalStorage(KEY_CUSTOM_USERNAME_SET);
|
const hasPreviouslySetCustomUsername = getLocalStorage(
|
||||||
|
KEY_CUSTOM_USERNAME_SET
|
||||||
|
);
|
||||||
if (hasPreviouslySetCustomUsername && !this.props.ignoreClient) {
|
if (hasPreviouslySetCustomUsername && !this.props.ignoreClient) {
|
||||||
this.sendJoinedMessage();
|
this.sendJoinedMessage();
|
||||||
}
|
}
|
||||||
@@ -229,30 +263,33 @@ export default class Chat extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
submitChat(content) {
|
submitChat(content) {
|
||||||
if (!content) {
|
if (!content) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { username } = this.props;
|
const { username } = this.props;
|
||||||
const message = {
|
const message = {
|
||||||
body: content,
|
body: content,
|
||||||
author: username,
|
author: username,
|
||||||
type: SOCKET_MESSAGE_TYPES.CHAT,
|
type: SOCKET_MESSAGE_TYPES.CHAT,
|
||||||
};
|
};
|
||||||
this.websocket.send(message);
|
this.websocket.send(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
sendJoinedMessage() {
|
sendJoinedMessage() {
|
||||||
const { username } = this.props;
|
const { username } = this.props;
|
||||||
const message = {
|
const message = {
|
||||||
username: username,
|
username: username,
|
||||||
type: SOCKET_MESSAGE_TYPES.USER_JOINED,
|
type: SOCKET_MESSAGE_TYPES.USER_JOINED,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Artificial delay so people who join and immediately
|
// Artificial delay so people who join and immediately
|
||||||
// leave don't get counted.
|
// leave don't get counted.
|
||||||
this.sendUserJoinedEvent = setTimeout(function() {
|
this.sendUserJoinedEvent = setTimeout(
|
||||||
this.websocket.send(message);
|
function () {
|
||||||
}.bind(this), 5000);
|
this.websocket.send(message);
|
||||||
|
}.bind(this),
|
||||||
|
5000
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateAuthorList(message) {
|
updateAuthorList(message) {
|
||||||
@@ -277,9 +314,12 @@ export default class Chat extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
checkShouldScroll() {
|
checkShouldScroll() {
|
||||||
const { scrollTop, scrollHeight, clientHeight } = this.scrollableMessagesContainer.current;
|
const { scrollTop, scrollHeight, clientHeight } =
|
||||||
|
this.scrollableMessagesContainer.current;
|
||||||
const fullyScrolled = scrollHeight - clientHeight;
|
const fullyScrolled = scrollHeight - clientHeight;
|
||||||
const shouldScroll = scrollHeight >= clientHeight && fullyScrolled - scrollTop < MESSAGE_JUMPTOBOTTOM_BUFFER;
|
const shouldScroll =
|
||||||
|
scrollHeight >= clientHeight &&
|
||||||
|
fullyScrolled - scrollTop < MESSAGE_JUMPTOBOTTOM_BUFFER;
|
||||||
return shouldScroll;
|
return shouldScroll;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,14 +356,19 @@ export default class Chat extends Component {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// update document title if window blurred
|
// update document title if window blurred
|
||||||
if (this.numMessagesSinceBlur && !this.props.messagesOnly && this.windowBlurred) {
|
if (
|
||||||
|
this.numMessagesSinceBlur &&
|
||||||
|
!this.props.messagesOnly &&
|
||||||
|
this.windowBlurred
|
||||||
|
) {
|
||||||
this.updateDocumentTitle();
|
this.updateDocumentTitle();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
updateDocumentTitle() {
|
updateDocumentTitle() {
|
||||||
const num = this.numMessagesSinceBlur > 10 ? '10+' : this.numMessagesSinceBlur;
|
const num =
|
||||||
|
this.numMessagesSinceBlur > 10 ? '10+' : this.numMessagesSinceBlur;
|
||||||
window.document.title = `${num} 💬 :: ${this.props.instanceTitle}`;
|
window.document.title = `${num} 💬 :: ${this.props.instanceTitle}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -331,14 +376,16 @@ export default class Chat extends Component {
|
|||||||
const { username, messagesOnly, chatInputEnabled } = props;
|
const { username, messagesOnly, chatInputEnabled } = props;
|
||||||
const { messages, chatUserNames, webSocketConnected } = state;
|
const { messages, chatUserNames, webSocketConnected } = state;
|
||||||
|
|
||||||
const messageList = messages.filter(message => message.visible !== false).map(
|
const messageList = messages
|
||||||
(message) =>
|
.filter((message) => message.visible !== false)
|
||||||
html`<${Message}
|
.map(
|
||||||
message=${message}
|
(message) =>
|
||||||
username=${username}
|
html`<${Message}
|
||||||
key=${message.id}
|
message=${message}
|
||||||
/>`
|
username=${username}
|
||||||
);
|
key=${message.id}
|
||||||
|
/>`
|
||||||
|
);
|
||||||
|
|
||||||
if (messagesOnly) {
|
if (messagesOnly) {
|
||||||
return html`
|
return html`
|
||||||
@@ -375,4 +422,3 @@ export default class Chat extends Component {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user