borrow react-ContentEditable component

This commit is contained in:
Ginger Wong 2020-08-17 01:12:21 -07:00
parent 979651a925
commit 70f3d7e165
3 changed files with 60 additions and 50 deletions

View File

@ -4,14 +4,16 @@ const html = htm.bind(h);
import { EmojiButton } from 'https://cdn.skypack.dev/@joeattardi/emoji-button'; import { EmojiButton } from 'https://cdn.skypack.dev/@joeattardi/emoji-button';
import { URL_CUSTOM_EMOJIS, getLocalStorage } from '../utils.js'; import { URL_CUSTOM_EMOJIS, getLocalStorage, setLocalStorage } from '../utils.js';
import { import {
KEY_CHAT_FIRST_MESSAGE_SENT, KEY_CHAT_FIRST_MESSAGE_SENT,
generatePlaceholderText, generatePlaceholderText,
getCaretPosition, getCaretPosition,
setCaretPosition,
} from '../utils/chat.js'; } from '../utils/chat.js';
import ContentEditable from './content-editable.js';
export default class ChatInput extends Component { export default class ChatInput extends Component {
constructor(props, context) { constructor(props, context) {
super(props, context); super(props, context);
@ -26,7 +28,7 @@ export default class ChatInput extends Component {
this.prepNewLine = false; this.prepNewLine = false;
this.state = { this.state = {
inputValue: '', inputHTML: '',
inputWarning: '', inputWarning: '',
hasSentFirstChatMessage: getLocalStorage(KEY_CHAT_FIRST_MESSAGE_SENT), hasSentFirstChatMessage: getLocalStorage(KEY_CHAT_FIRST_MESSAGE_SENT),
}; };
@ -38,9 +40,10 @@ export default class ChatInput extends Component {
this.handleMessageInputKeydown = this.handleMessageInputKeydown.bind(this); this.handleMessageInputKeydown = this.handleMessageInputKeydown.bind(this);
this.handleMessageInputKeyup = this.handleMessageInputKeyup.bind(this); this.handleMessageInputKeyup = this.handleMessageInputKeyup.bind(this);
this.handleMessageInputBlur = this.handleMessageInputBlur.bind(this); this.handleMessageInputBlur = this.handleMessageInputBlur.bind(this);
this.handleMessageInput = this.handleMessageInput.bind(this);
this.handleSubmitChatButton = this.handleSubmitChatButton.bind(this); this.handleSubmitChatButton = this.handleSubmitChatButton.bind(this);
this.handlePaste = this.handlePaste.bind(this); this.handlePaste = this.handlePaste.bind(this);
this.handleContentEditableChange = this.handleContentEditableChange.bind(this);
} }
componentDidMount() { componentDidMount() {
@ -83,6 +86,7 @@ export default class ChatInput extends Component {
} }
handleEmojiSelected(emoji) { handleEmojiSelected(emoji) {
const { inputHTML } = this.state;
let content = ''; let content = '';
if (emoji.url) { if (emoji.url) {
const url = location.protocol + "//" + location.host + "/" + emoji.url; const url = location.protocol + "//" + location.host + "/" + emoji.url;
@ -92,21 +96,22 @@ export default class ChatInput extends Component {
content = emoji.emoji; content = emoji.emoji;
} }
this.formMessageInput.current.innerHTML += content; this.setState({
inputHTML: inputHTML + content,
});
} }
// autocomplete user names // autocomplete user names
autoCompleteNames() { autoCompleteNames() {
const { chatUserNames } = this.props; const { chatUserNames } = this.props;
const rawValue = this.formMessageInput.current.innerHTML; const { inputHTML } = this.state;
const position = getCaretPosition(this.formMessageInput); const position = getCaretPosition(this.formMessageInput.current);
const at = rawValue.lastIndexOf('@', position - 1); const at = inputHTML.lastIndexOf('@', position - 1);
if (at === -1) { if (at === -1) {
return false; return false;
} }
const partial = rawValue.substring(at + 1, position).trim(); const partial = inputHTML.substring(at + 1, position).trim();
if (partial === this.suggestion) { if (partial === this.suggestion) {
partial = this.partial; partial = this.partial;
@ -125,9 +130,9 @@ export default class ChatInput extends Component {
if (possibilities.length > 0) { if (possibilities.length > 0) {
this.suggestion = possibilities[this.completionIndex]; this.suggestion = possibilities[this.completionIndex];
// TODO: Fix the space not working. I'm guessing because the DOM ignores spaces and it requires a nbsp or something? this.setState({
this.formMessageInput.current.innerHTML = rawValue.substring(0, at + 1) + this.suggestion + ' ' + rawValue.substring(position); inputHTML: inputHTML.substring(0, at + 1) + this.suggestion + ' ' + inputHTML.substring(position),
setCaretPosition(this.formMessageInput.current, at + this.suggestion.length + 2); })
} }
return true; return true;
@ -136,9 +141,10 @@ export default class ChatInput extends Component {
handleMessageInputKeydown(event) { handleMessageInputKeydown(event) {
const okCodes = [37,38,39,40,16,91,18,46,8]; const okCodes = [37,38,39,40,16,91,18,46,8];
const formField = this.formMessageInput.current; const formField = this.formMessageInput.current;
const htmlValue = formField.innerHTML.trim();
let textValue = formField.innerText.trim(); let textValue = formField.innerText.trim(); // get this only to count chars
let numCharsLeft = this.maxMessageLength - textValue.length;
let numCharsLeft = this.maxMessageLength - textValue.length;
if (event.keyCode === 13) { // enter if (event.keyCode === 13) { // enter
if (!this.prepNewLine) { if (!this.prepNewLine) {
this.sendMessage(); this.sendMessage();
@ -154,7 +160,7 @@ export default class ChatInput extends Component {
if (this.autoCompleteNames()) { if (this.autoCompleteNames()) {
event.preventDefault(); event.preventDefault();
// value could have been changed, update variables // value could have been changed, update char count
textValue = formField.innerText.trim(); textValue = formField.innerText.trim();
numCharsLeft = this.maxMessageLength - textValue.length; numCharsLeft = this.maxMessageLength - textValue.length;
} }
@ -186,10 +192,6 @@ export default class ChatInput extends Component {
this.prepNewLine = false; this.prepNewLine = false;
} }
handleMessageInput(event) {
console.log("========on input",event.target, this.formMessageInput.current.innerHTML, this.formMessageInput.current.innerText);
}
handlePaste(event) { handlePaste(event) {
event.preventDefault(); event.preventDefault();
document.execCommand('inserttext', false, event.clipboardData.getData('text/plain')); document.execCommand('inserttext', false, event.clipboardData.getData('text/plain'));
@ -202,10 +204,11 @@ export default class ChatInput extends Component {
sendMessage() { sendMessage() {
const { handleSendMessage } = this.props; const { handleSendMessage } = this.props;
const { hasSentFirstChatMessage } = this.state; const { hasSentFirstChatMessage, inputHTML } = this.state;
const message = this.formMessageInput.current.innerHTML.trim(); const message = inputHTML.trim();
const newStates = { const newStates = {
inputWarning: '', inputWarning: '',
inputHTML: '',
}; };
handleSendMessage(message); handleSendMessage(message);
@ -217,11 +220,14 @@ export default class ChatInput extends Component {
// clear things out. // clear things out.
this.setState(newStates); this.setState(newStates);
this.formMessageInput.current.innerHTML = ''; }
handleContentEditableChange(event) {
this.setState({ inputHTML: event.target.value });
} }
render(props, state) { render(props, state) {
const { hasSentFirstChatMessage, inputWarning } = state; const { hasSentFirstChatMessage, inputWarning, inputHTML } = state;
const { inputEnabled } = props; const { inputEnabled } = props;
const emojiButtonStyle = { const emojiButtonStyle = {
display: this.emojiPicker ? 'block' : 'none', display: this.emojiPicker ? 'block' : 'none',
@ -231,17 +237,22 @@ export default class ChatInput extends Component {
return ( return (
html` html`
<div id="message-input-container" class="shadow-md bg-gray-900 border-t border-gray-700 border-solid"> <div id="message-input-container" class="shadow-md bg-gray-900 border-t border-gray-700 border-solid">
<div
<${ContentEditable}
class="appearance-none block w-full bg-gray-200 text-gray-700 border border-black-500 rounded py-2 px-2 my-2 focus:bg-white" class="appearance-none block w-full bg-gray-200 text-gray-700 border border-black-500 rounded py-2 px-2 my-2 focus:bg-white"
onkeydown=${this.handleMessageInputKeydown} placeholderText=${placeholderText}
onkeyup=${this.handleMessageInputKeyup}
onblur=${this.handleMessageInputBlur} innerRef=${this.formMessageInput}
oninput=${this.handleMessageInput} html=${inputHTML}
onpaste=${this.handlePaste} disabled=${!inputEnabled}
contenteditable=${inputEnabled} onChange=${this.handleContentEditableChange}
placeholder=${placeholderText} onKeyDown=${this.handleMessageInputKeydown}
ref=${this.formMessageInput} onKeyUp=${this.handleMessageInputKeyup}
></div> onBlur=${this.handleMessageInputBlur}
onPaste=${this.handlePaste}
/>
<button <button
type="button" type="button"
style=${emojiButtonStyle} style=${emojiButtonStyle}

View File

@ -128,17 +128,17 @@ export default class Chat extends Component {
this.disableChat() this.disableChat()
} }
handleSubmitChatButton(event) { // handleSubmitChatButton(event) {
const { inputValue } = this.state; // const { inputValue } = this.state;
var value = inputValue.trim(); // var value = inputValue.trim();
if (value) { // if (value) {
this.submitChat(value); // this.submitChat(value);
event.preventDefault(); // event.preventDefault();
return false; // return false;
} // }
event.preventDefault(); // event.preventDefault();
return false; // return false;
} // }
submitChat(content) { submitChat(content) {
if (!content) { if (!content) {

View File

@ -21,13 +21,12 @@ export function formatMessageText(message, username) {
}).makeHtml(message); }).makeHtml(message);
formattedText = linkify(formattedText, message); formattedText = linkify(formattedText, message);
formattedText = highlightUsername(formattedText, username); // formattedText = highlightUsername(formattedText, username);
return addNewlines(formattedText); return addNewlines(formattedText);
} }
function highlightUsername(message, username) { function highlightUsername(message, username) {
// const username = document.getElementById('self-message-author').value;
const pattern = new RegExp('@?' + username.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi'); const pattern = new RegExp('@?' + username.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi');
return message.replace(pattern, '<span class="highlighted">$&</span>'); return message.replace(pattern, '<span class="highlighted">$&</span>');
} }
@ -126,7 +125,7 @@ function getInstagramEmbedFromURL(url) {
} }
function isImage(url) { function isImage(url) {
const re = /\.(jpe?g|png|gif)$/; const re = /\.(jpe?g|png|gif)$/i;
const isImage = re.test(url); const isImage = re.test(url);
return isImage; return isImage;
} }
@ -135,7 +134,6 @@ function getImageForURL(url) {
return `<a target="_blank" href="${url}"><img class="embedded-image" src="${url}" width="100%" height="150px"/></a>`; return `<a target="_blank" href="${url}"><img class="embedded-image" src="${url}" width="100%" height="150px"/></a>`;
} }
// Taken from https://stackoverflow.com/questions/3972014/get-contenteditable-caret-index-position // Taken from https://stackoverflow.com/questions/3972014/get-contenteditable-caret-index-position
export function getCaretPosition(editableDiv) { export function getCaretPosition(editableDiv) {
var caretPos = 0, var caretPos = 0,
@ -162,6 +160,7 @@ export function getCaretPosition(editableDiv) {
return caretPos; return caretPos;
} }
// Might not need this anymore
// Pieced together from parts of https://stackoverflow.com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div // Pieced together from parts of https://stackoverflow.com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div
export function setCaretPosition(editableDiv, position) { export function setCaretPosition(editableDiv, position) {
var range = document.createRange(); var range = document.createRange();