const messageInputTemplate = document.createElement('template');
messageInputTemplate.innerHTML = `
`;
// stop button
class MessageInput extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(messageInputTemplate.content.cloneNode(true));
this._messageInputField = shadowRoot.querySelector('#messageInputField');
this._sendButton = shadowRoot.querySelector('#sendButton');
this._messageInputField.addEventListener('keydown', this._handleKeyDown.bind(this));
this._sendButton.addEventListener('click', this._handleClick.bind(this));
}
connectedCallback() {
// Set focus to the input field when the element is added to the DOM
this._messageInputField.focus();
}
init(worker) {
this.worker = worker;
}
setMessagesArea(messagesAreaComponent) {
this.messagesAreaComponent = messagesAreaComponent;
}
handleMessageSent() {
console.log("handleMessageSent");
this._messageInputField.value = '';
this._sendButton.removeAttribute('disabled');
this._messageInputField.removeAttribute('disabled');
}
_handleKeyDown(event) {
if (event.key === 'Enter') {
this._handleNewChatMessage();
}
}
_handleClick() {
this._handleNewChatMessage();
}
_handleNewChatMessage() {
// prevent user from interacting while we're waiting
this._sendButton.setAttribute('disabled', 'disabled');
this._messageInputField.setAttribute('disabled', 'disabled');
let messageContent = this._messageInputField.value;
if (this.messagesAreaComponent) {
this.messagesAreaComponent.appendUserMessage(messageContent);
}
this.worker.postMessage({ type: 'chatMessage', message: messageContent });
}
}
customElements.define('message-input', MessageInput);