forked from retoor/snek
feat: add ChatInputElement web component with textarea and send button
Implement a custom HTML element 'chat-input' that provides a styled textarea and send button. The component dispatches custom events for input, change, and submit actions, with Enter key support for submission and automatic button disabling when the textarea is empty.
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
|
||||
|
||||
class ChatInputElement extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
this.attachShadow({ mode: 'open' });
|
||||
this.component = document.createElement('div');
|
||||
this.shadowRoot.appendChild(this.component);
|
||||
}
|
||||
connectedCallback() {
|
||||
const link = document.createElement("link")
|
||||
link.rel = 'stylesheet'
|
||||
link.href = '/base.css'
|
||||
this.component.appendChild(link)
|
||||
this.container = document.createElement('div')
|
||||
this.container.classList.add("chat-input")
|
||||
this.container.innerHTML = `
|
||||
<textarea placeholder="Type a message..." rows="2"></textarea>
|
||||
<button>Send</button>
|
||||
`;
|
||||
this.container.querySelector('textarea').addEventListener('input', (e) => {
|
||||
this.dispatchEvent(new CustomEvent("input", {detail:e.target.value,bubbles:true}))
|
||||
const message = e.target.value;
|
||||
const button = this.container.querySelector('button');
|
||||
button.disabled = !message;
|
||||
})
|
||||
this.container.querySelector('textarea').addEventListener('change',(e)=>{
|
||||
this.dispatchEvent(new CustomEvent("change", {detail:e.target.value,bubbles:true}))
|
||||
console.error(e.target.value)
|
||||
})
|
||||
this.container.querySelector('textarea').addEventListener('keyup', (e) => {
|
||||
if(e.key == 'Enter' && !e.shiftKey){
|
||||
this.dispatchEvent(new CustomEvent("submit", {detail:e.target.value,bubbles:true}))
|
||||
e.target.value = ''
|
||||
}
|
||||
})
|
||||
this.component.appendChild(this.container)
|
||||
}
|
||||
}
|
||||
customElements.define('chat-input', ChatInputElement);
|
||||
Reference in New Issue
Block a user