reorganize js files

This commit is contained in:
Ginger Wong
2020-08-23 19:06:58 -07:00
parent 786b4c04fa
commit 4b28ed8f25
20 changed files with 316 additions and 594 deletions

View File

@@ -1,283 +0,0 @@
import { h, Component, createRef } from 'https://unpkg.com/preact?module';
import htm from 'https://unpkg.com/htm?module';
const html = htm.bind(h);
import { EmojiButton } from 'https://cdn.skypack.dev/@joeattardi/emoji-button';
import { URL_CUSTOM_EMOJIS, getLocalStorage, setLocalStorage } from '../utils.js';
import {
KEY_CHAT_FIRST_MESSAGE_SENT,
generatePlaceholderText,
getCaretPosition,
} from '../utils/chat.js';
import ContentEditable from './content-editable.js';
export default class ChatInput extends Component {
constructor(props, context) {
super(props, context);
this.formMessageInput = createRef();
this.emojiPickerButton = createRef();
this.messageCharCount = 0;
this.maxMessageLength = 500;
this.maxMessageBuffer = 20;
this.emojiPicker = null;
this.prepNewLine = false;
this.state = {
inputHTML: '',
inputWarning: '',
hasSentFirstChatMessage: getLocalStorage(KEY_CHAT_FIRST_MESSAGE_SENT),
};
this.handleEmojiButtonClick = this.handleEmojiButtonClick.bind(this);
this.handleEmojiSelected = this.handleEmojiSelected.bind(this);
this.getCustomEmojis = this.getCustomEmojis.bind(this);
this.handleMessageInputKeydown = this.handleMessageInputKeydown.bind(this);
this.handleMessageInputKeyup = this.handleMessageInputKeyup.bind(this);
this.handleMessageInputBlur = this.handleMessageInputBlur.bind(this);
this.handleSubmitChatButton = this.handleSubmitChatButton.bind(this);
this.handlePaste = this.handlePaste.bind(this);
this.handleContentEditableChange = this.handleContentEditableChange.bind(this);
}
componentDidMount() {
this.getCustomEmojis();
}
getCustomEmojis() {
fetch(URL_CUSTOM_EMOJIS)
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok ${response.ok}`);
}
return response.json();
})
.then(json => {
this.emojiPicker = new EmojiButton({
zIndex: 100,
theme: 'dark',
custom: json,
initialCategory: 'custom',
showPreview: false,
emojiSize: '30px',
emojisPerRow: 6,
position: 'top'
});
this.emojiPicker.on('emoji', emoji => {
this.handleEmojiSelected(emoji);
});
})
.catch(error => {
// this.handleNetworkingError(`Emoji Fetch: ${error}`);
});
}
handleEmojiButtonClick() {
if (this.emojiPicker) {
this.emojiPicker.togglePicker(this.emojiPickerButton.current);
}
}
handleEmojiSelected(emoji) {
const { inputHTML } = this.state;
let content = '';
if (emoji.url) {
const url = location.protocol + "//" + location.host + "/" + emoji.url;
const name = url.split('\\').pop().split('/').pop();
content = "<img class=\"emoji\" alt=\"" + name + "\" src=\"" + url + "\"/>";
} else {
content = emoji.emoji;
}
this.setState({
inputHTML: inputHTML + content,
});
}
// autocomplete user names
autoCompleteNames() {
const { chatUserNames } = this.props;
const { inputHTML } = this.state;
const position = getCaretPosition(this.formMessageInput.current);
const at = inputHTML.lastIndexOf('@', position - 1);
if (at === -1) {
return false;
}
let partial = inputHTML.substring(at + 1, position).trim();
if (partial === this.suggestion) {
partial = this.partial;
} else {
this.partial = partial;
}
const possibilities = chatUserNames.filter(function (username) {
return username.toLowerCase().startsWith(partial.toLowerCase());
});
if (this.completionIndex === undefined || ++this.completionIndex >= possibilities.length) {
this.completionIndex = 0;
}
if (possibilities.length > 0) {
this.suggestion = possibilities[this.completionIndex];
this.setState({
inputHTML: inputHTML.substring(0, at + 1) + this.suggestion + ' ' + inputHTML.substring(position),
})
}
return true;
}
handleMessageInputKeydown(event) {
const okCodes = [37,38,39,40,16,91,18,46,8];
const formField = this.formMessageInput.current;
let textValue = formField.innerText.trim(); // get this only to count chars
let numCharsLeft = this.maxMessageLength - textValue.length;
if (event.keyCode === 13) { // enter
if (!this.prepNewLine) {
this.sendMessage();
event.preventDefault();
this.prepNewLine = false;
return;
}
}
if (event.keyCode === 16 || event.keyCode === 17) { // ctrl, shift
this.prepNewLine = true;
}
if (event.keyCode === 9) { // tab
if (this.autoCompleteNames()) {
event.preventDefault();
// value could have been changed, update char count
textValue = formField.innerText.trim();
numCharsLeft = this.maxMessageLength - textValue.length;
}
}
// text count
if (numCharsLeft <= this.maxMessageBuffer) {
this.setState({
inputWarning: `${numCharsLeft} chars left`,
});
if (numCharsLeft <= 0 && !okCodes.includes(event.keyCode)) {
event.preventDefault(); // prevent typing more
return;
}
} else {
this.setState({
inputWarning: '',
});
}
}
handleMessageInputKeyup(event) {
if (event.keyCode === 16 || event.keyCode === 17) { // ctrl, shift
this.prepNewLine = false;
}
}
handleMessageInputBlur(event) {
this.prepNewLine = false;
}
handlePaste(event) {
event.preventDefault();
document.execCommand('inserttext', false, event.clipboardData.getData('text/plain'));
}
handleSubmitChatButton(event) {
event.preventDefault();
this.sendMessage();
}
sendMessage() {
const { handleSendMessage } = this.props;
const { hasSentFirstChatMessage, inputHTML } = this.state;
const message = inputHTML.trim();
const newStates = {
inputWarning: '',
inputHTML: '',
};
handleSendMessage(message);
if (!hasSentFirstChatMessage) {
newStates.hasSentFirstChatMessage = true;
setLocalStorage(KEY_CHAT_FIRST_MESSAGE_SENT, true);
}
// clear things out.
this.setState(newStates);
}
handleContentEditableChange(event) {
this.setState({ inputHTML: event.target.value });
}
render(props, state) {
const { hasSentFirstChatMessage, inputWarning, inputHTML } = state;
const { inputEnabled } = props;
const emojiButtonStyle = {
display: this.emojiPicker ? 'block' : 'none',
};
const placeholderText = generatePlaceholderText(inputEnabled, hasSentFirstChatMessage);
return (
html`
<div id="message-input-container" class="w-full shadow-md bg-gray-900 border-t border-gray-700 border-solid p-4">
<${ContentEditable}
id="message-input"
class="appearance-none block w-full bg-gray-200 text-sm text-gray-700 border border-black-500 rounded py-2 px-2 my-2 focus:bg-white h-20 overflow-auto"
placeholderText=${placeholderText}
innerRef=${this.formMessageInput}
html=${inputHTML}
disabled=${!inputEnabled}
onChange=${this.handleContentEditableChange}
onKeyDown=${this.handleMessageInputKeydown}
onKeyUp=${this.handleMessageInputKeyup}
onBlur=${this.handleMessageInputBlur}
onPaste=${this.handlePaste}
/>
<div id="message-form-actions" class="flex flex-row justify-between items-center w-full">
<span id="message-form-warning" class="text-red-600 text-xs">${inputWarning}</span>
<div id="message-form-actions-buttons" class="flex flex-row justify-end items-center">
<button
ref=${this.emojiPickerButton}
id="emoji-button"
class="mr-2 text-2xl cursor-pointer"
type="button"
style=${emojiButtonStyle}
onclick=${this.handleEmojiButtonClick}
>😏</button>
<button
onclick=${this.handleSubmitChatButton}
type="button"
id="button-submit-message"
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-2 rounded"
> Chat
</button>
</div>
</div>
</div>
`);
}
}

View File

@@ -1,201 +0,0 @@
import { h, Component } from 'https://unpkg.com/preact?module';
import htm from 'https://unpkg.com/htm?module';
// Initialize htm with Preact
const html = htm.bind(h);
import SOCKET_MESSAGE_TYPES from '../utils/socket-message-types.js';
import Message from './message.js';
import ChatInput from './chat-input.js';
import { CALLBACKS } from '../websocket.js';
import { URL_CHAT_HISTORY, setVHvar, hasTouchScreen } from '../utils.js';
import { extraUserNamesFromMessageHistory } from '../utils/chat.js';
export default class Chat extends Component {
constructor(props, context) {
super(props, context);
this.state = {
inputEnabled: true,
messages: [],
chatUserNames: [],
};
this.websocket = null;
this.getChatHistory = this.getChatHistory.bind(this);
this.receivedWebsocketMessage = this.receivedWebsocketMessage.bind(this);
this.websocketDisconnected = this.websocketDisconnected.bind(this);
// this.handleSubmitChatButton = this.handleSubmitChatButton.bind(this);
this.submitChat = this.submitChat.bind(this);
}
componentDidMount() {
this.setupWebSocketCallbacks();
this.getChatHistory();
if (hasTouchScreen()) {
setVHvar();
window.addEventListener("orientationchange", setVHvar);
// this.tagAppContainer.classList.add('touch-screen');
}
}
componentDidUpdate(prevProps) {
const { username: prevName } = prevProps;
const { username, userAvatarImage } = this.props;
// if username updated, send a message
if (prevName !== username) {
this.sendUsernameChange(prevName, username, userAvatarImage);
}
}
setupWebSocketCallbacks() {
this.websocket = this.props.websocket;
if (this.websocket) {
this.websocket.addListener(CALLBACKS.RAW_WEBSOCKET_MESSAGE_RECEIVED, this.receivedWebsocketMessage);
this.websocket.addListener(CALLBACKS.WEBSOCKET_DISCONNECTED, this.websocketDisconnected);
}
}
// fetch chat history
getChatHistory() {
fetch(URL_CHAT_HISTORY)
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok ${response.ok}`);
}
return response.json();
})
.then(data => {
// extra user names
const chatUserNames = extraUserNamesFromMessageHistory(data);
this.setState({
messages: data,
chatUserNames,
});
})
.catch(error => {
// this.handleNetworkingError(`Fetch getChatHistory: ${error}`);
});
}
sendUsernameChange(oldName, newName, image) {
const nameChange = {
type: SOCKET_MESSAGE_TYPES.NAME_CHANGE,
oldName: oldName,
newName: newName,
image: image,
};
this.websocket.send(nameChange);
}
receivedWebsocketMessage(message) {
this.addMessage(message);
}
// if incoming message has same id as existing message, don't add it
addMessage(message) {
const { messages: curMessages } = this.state;
const existing = curMessages.filter(function (item) {
return item.id === message.id;
})
if (existing.length === 0 || !existing) {
const newState = {
messages: [...curMessages, message],
};
const updatedChatUserNames = this.updateAuthorList(message);
if (updatedChatUserNames.length) {
newState.chatUserNames = [...updatedChatUserNames];
}
this.setState(newState);
}
// todo - jump to bottom
// jumpToBottom(this.scrollableMessagesContainer);
}
websocketDisconnected() {
// this.websocket = null;
this.disableChat();
}
submitChat(content) {
if (!content) {
return;
}
const { username, userAvatarImage } = this.props;
const message = {
body: content,
author: username,
image: userAvatarImage,
type: SOCKET_MESSAGE_TYPES.CHAT,
};
this.websocket.send(message);
}
disableChat() {
this.setState({
inputEnabled: false,
});
}
enableChat() {
this.setState({
inputEnabled: true,
});
}
updateAuthorList(message) {
const { type } = message;
const nameList = this.state.chatUserNames;
if (
type === SOCKET_MESSAGE_TYPES.CHAT &&
!nameList.includes(message.author)
) {
return nameList.push(message.author);
} else if (type === SOCKET_MESSAGE_TYPES.NAME_CHANGE) {
const { oldName, newName } = message;
const oldNameIndex = nameList.indexOf(oldName);
return nameList.splice(oldNameIndex, 1, newName);
}
return [];
}
render(props, state) {
const { username, messagesOnly, chatEnabled } = props;
const { messages, inputEnabled, chatUserNames } = state;
const messageList = messages.map((message) => (html`<${Message} message=${message} username=${username} key=${message.id} />`));
if (messagesOnly) {
return (
html`
<div id="messages-container" class="py-1 overflow-auto">
${messageList}
</div>
`);
}
return (
html`
<section id="chat-container-wrap" class="flex flex-col">
<div id="chat-container" class="bg-gray-800 flex flex-col justify-end overflow-auto">
<div id="messages-container" class="py-1 overflow-auto">
${messageList}
</div>
<${ChatInput}
chatUserNames=${chatUserNames}
inputEnabled=${chatEnabled && inputEnabled}
handleSendMessage=${this.submitChat}
/>
</div>
</section>
`);
}
}

View File

@@ -1,131 +0,0 @@
/*
Since we can't really import react-contenteditable here, I'm borrowing code for this component from here:
github.com/lovasoa/react-contenteditable/
and here:
https://stackoverflow.com/questions/22677931/react-js-onchange-event-for-contenteditable/27255103#27255103
*/
import { Component, createRef, createElement } from 'https://unpkg.com/preact?module';
function replaceCaret(el) {
// Place the caret at the end of the element
const target = document.createTextNode('');
el.appendChild(target);
// do not move caret if element was not focused
const isTargetFocused = document.activeElement === el;
if (target !== null && target.nodeValue !== null && isTargetFocused) {
var sel = window.getSelection();
if (sel !== null) {
var range = document.createRange();
range.setStart(target, target.nodeValue.length);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
if (el) el.focus();
}
}
function normalizeHtml(str) {
return str && str.replace(/&nbsp;|\u202F|\u00A0/g, ' ');
}
export default class ContentEditable extends Component {
constructor(props) {
super(props);
this.el = createRef();
this.lastHtml = '';
this.emitChange = this.emitChange.bind(this);
this.getDOMElement = this.getDOMElement.bind(this);
}
shouldComponentUpdate(nextProps) {
const { props } = this;
const el = this.getDOMElement();
// We need not rerender if the change of props simply reflects the user's edits.
// Rerendering in this case would make the cursor/caret jump
// Rerender if there is no element yet... (somehow?)
if (!el) return true;
// ...or if html really changed... (programmatically, not by user edit)
if (
normalizeHtml(nextProps.html) !== normalizeHtml(el.innerHTML)
) {
return true;
}
// Handle additional properties
return props.disabled !== nextProps.disabled ||
props.tagName !== nextProps.tagName ||
props.className !== nextProps.className ||
props.innerRef !== nextProps.innerRef;
}
componentDidUpdate() {
const el = this.getDOMElement();
if (!el) return;
// Perhaps React (whose VDOM gets outdated because we often prevent
// rerendering) did not update the DOM. So we update it manually now.
if (this.props.html !== el.innerHTML) {
el.innerHTML = this.props.html;
}
this.lastHtml = this.props.html;
replaceCaret(el);
}
getDOMElement() {
return (this.props.innerRef && typeof this.props.innerRef !== 'function' ? this.props.innerRef : this.el).current;
}
emitChange(originalEvt) {
const el = this.getDOMElement();
if (!el) return;
const html = el.innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
// Clone event with Object.assign to avoid
// "Cannot assign to read only property 'target' of object"
const evt = Object.assign({}, originalEvt, {
target: {
value: html
}
});
this.props.onChange(evt);
}
this.lastHtml = html;
}
render(props) {
const { html, innerRef } = props;
return createElement(
'div',
{
...props,
ref: typeof innerRef === 'function' ? (current) => {
innerRef(current)
this.el.current = current
} : innerRef || this.el,
onInput: this.emitChange,
onBlur: this.props.onBlur || this.emitChange,
onKeyup: this.props.onKeyUp || this.emitChange,
onKeydown: this.props.onKeyDown || this.emitChange,
contentEditable: !this.props.disabled,
dangerouslySetInnerHTML: { __html: html },
},
this.props.children,
);
}
}

View File

@@ -1,59 +0,0 @@
import { html, Component } from "https://unpkg.com/htm/preact/index.mjs?module";
import { messageBubbleColorForString } from '../utils/user-colors.js';
import { formatMessageText } from '../utils/chat.js';
import { generateAvatar } from '../utils.js';
import SOCKET_MESSAGE_TYPES from '../utils/socket-message-types.js';
export default class Message extends Component {
render(props) {
const { message, username } = props;
const { type } = message;
if (type === SOCKET_MESSAGE_TYPES.CHAT) {
const { image, author, body } = message;
const formattedMessage = formatMessageText(body, username);
const avatar = image || generateAvatar(author);
const authorColor = messageBubbleColorForString(author);
const avatarBgColor = { backgroundColor: authorColor };
const authorTextColor = { color: authorColor };
return (
html`
<div class="message flex flex-row align-start p-3">
<div
class="message-avatar rounded-full flex items-center justify-center mr-3"
style=${avatarBgColor}
>
<img src=${avatar} class="p-1" />
</div>
<div class="message-content text-sm break-words">
<div class="message-author text-white font-bold" style=${authorTextColor}>
${author}
</div>
<div
class="message-text text-gray-300 font-normal"
dangerouslySetInnerHTML=${
{ __html: formattedMessage }
}
></div>
</div>
</div>
`);
} else if (type === SOCKET_MESSAGE_TYPES.NAME_CHANGE) {
const { oldName, newName, image } = message;
return (
html`
<div class="message flex align-start p3">
<div class="message-content text-sm">
<img class="mr-2" src=${image} />
<div class="text-white text-center">
<span class="font-bold">${oldName}</span> is now known as <span class="font-bold">${newName}</span>.
</div>
</div>
</div>
`
);
}
}
}

View File

@@ -1,76 +0,0 @@
import { h, Component, Fragment } from 'https://unpkg.com/preact?module';
import htm from 'https://unpkg.com/htm?module';
const html = htm.bind(h);
import UsernameForm from './username.js';
import Chat from './chat.js';
import Websocket from '../websocket.js';
import { getLocalStorage, generateAvatar, generateUsername } from '../utils.js';
import { KEY_USERNAME, KEY_AVATAR } from '../utils/chat.js';
export default class StandaloneChat extends Component {
constructor(props, context) {
super(props, context);
this.state = {
websocket: new Websocket(),
chatEnabled: true, // always true for standalone chat
username: getLocalStorage(KEY_USERNAME) || generateUsername(),
userAvatarImage: getLocalStorage(KEY_AVATAR) || generateAvatar(`${this.username}${Date.now()}`),
};
this.websocket = null;
this.handleUsernameChange = this.handleUsernameChange.bind(this);
}
handleUsernameChange(newName, newAvatar) {
this.setState({
username: newName,
userAvatarImage: newAvatar,
});
}
handleChatToggle() {
return;
}
render(props, state) {
const { messagesOnly } = props;
const { username, userAvatarImage, websocket } = state;
if (messagesOnly) {
return (
html`
<${Chat}
websocket=${websocket}
username=${username}
userAvatarImage=${userAvatarImage}
messagesOnly
/>
`);
}
// not needed for standalone, just messages only. remove later.
return (
html`
<${Fragment}>
<${UsernameForm}
username=${username}
userAvatarImage=${userAvatarImage}
handleUsernameChange=${this.handleUsernameChange}
handleChatToggle=${this.handleChatToggle}
/>
<${Chat}
websocket=${websocket}
username=${username}
userAvatarImage=${userAvatarImage}
/>
</${Fragment}>
`);
}
}

View File

@@ -1,107 +0,0 @@
import { h, Component, createRef } from 'https://unpkg.com/preact?module';
import htm from 'https://unpkg.com/htm?module';
// Initialize htm with Preact
const html = htm.bind(h);
import { generateAvatar, setLocalStorage } from '../utils.js';
import { KEY_USERNAME, KEY_AVATAR } from '../utils/chat.js';
export default class UsernameForm extends Component {
constructor(props, context) {
super(props, context);
this.state = {
displayForm: false,
};
this.textInput = createRef();
this.handleKeydown = this.handleKeydown.bind(this);
this.handleDisplayForm = this.handleDisplayForm.bind(this);
this.handleHideForm = this.handleHideForm.bind(this);
this.handleUpdateUsername = this.handleUpdateUsername.bind(this);
}
handleDisplayForm() {
this.setState({
displayForm: true,
});
}
handleHideForm() {
this.setState({
displayForm: false,
});
}
handleKeydown(event) {
if (event.keyCode === 13) { // enter
this.handleUpdateUsername();
} else if (event.keyCode === 27) { // esc
this.handleHideForm();
}
}
handleUpdateUsername() {
const { username: curName, handleUsernameChange } = this.props;
let newName = this.textInput.current.value;
newName = newName.trim();
if (newName !== '' && newName !== curName) {
const newAvatar = generateAvatar(`${newName}${Date.now()}`);
setLocalStorage(KEY_USERNAME, newName);
setLocalStorage(KEY_AVATAR, newAvatar);
if (handleUsernameChange) {
handleUsernameChange(newName, newAvatar);
}
this.handleHideForm();
}
}
render(props, state) {
const { username, userAvatarImage } = props;
const { displayForm } = state;
const narrowSpace = document.body.clientWidth < 640;
const styles = {
info: {
display: displayForm || narrowSpace ? 'none' : 'flex',
},
form: {
display: displayForm ? 'flex' : 'none',
},
};
if (narrowSpace) {
styles.form.display = 'inline-block';
}
return (
html`
<div id="user-info">
<div id="user-info-display" style=${styles.info} title="Click to update user name" class="flex flex-row justify-end items-center cursor-pointer py-2 px-4 overflow-hidden w-full opacity-1 transition-opacity duration-200 hover:opacity-75" onClick=${this.handleDisplayForm}>
<img
src=${userAvatarImage}
alt=""
id="username-avatar"
class="rounded-full bg-black bg-opacity-50 border border-solid border-gray-700 mr-2 h-8 w-8"
/>
<span id="username-display" class="text-indigo-600 text-xs font-semibold truncate overflow-hidden whitespace-no-wrap">${username}</span>
</div>
<div id="user-info-change" class="flex flex-no-wrap p-1 items-center justify-end" style=${styles.form}>
<input type="text"
id="username-change-input"
class="appearance-none block w-full bg-gray-200 text-gray-700 border border-black-500 rounded py-1 px-1 leading-tight text-xs focus:bg-white"
maxlength="100"
placeholder="Update username"
value=${username}
onKeydown=${this.handleKeydown}
ref=${this.textInput}
/>
<button id="button-update-username" onClick=${this.handleUpdateUsername} type="button" class="bg-blue-500 hover:bg-blue-700 text-white text-xs uppercase p-1 mx-1 rounded cursor-pointer user-btn">Update</button>
<button id="button-cancel-change" onClick=${this.handleHideForm} type="button" class="bg-gray-900 hover:bg-gray-800 py-1 px-2 mx-1 rounded cursor-pointer user-btn text-white text-xs uppercase text-opacity-50" title="cancel">X</button>
</div>
</div>
`);
}
}