import { Span, Button, List, ListItem, Input, createElement } from './weigets.js' // 先不划分频道, 只有一个公共聊天室 export default class Chat { constructor({ EventListeners = {}, onsend, onexit }) { this.event = { onsend, onexit } this.ul = List({ classList: ['chat-list'] }) this.EventListeners = EventListeners document.body.appendChild(this.ul) // 元素加入页面 // 使用一个有序列表来存储消息 const messageBox = new Map() // 添加输入框 const input = createElement({ type: 'text', placeholder: '输入聊天内容', style: { height: '5rem', margin: '1rem 2rem', padding: '1rem', boxSizing: 'border-box', boxShadow: '0 0 1rem #eee', }, onkeydown: event => { if (event.key === 'Enter') { const text = input.value.trim() if (text) { this.send(text) input.value = '' } } } }, 'textarea') document.body.appendChild(input) // 写入 css 样式到 head const style = document.createElement('style') style.innerText = ` ul.chat-list { max-height: 70vh; overflow-y: auto; } ul.chat-list > li > span { cursor: pointer; } ul.chat-list > li.play > span { color: #02be08; } ul.chat-list > li.cache::marker { color: #02be08; font-size: 1em; contentx: '⚡'; } ul.chat-list > li.disable { color: #888; } ` document.head.appendChild(style) } // 收到应答(对方确认消息已被接收) answer(data) { const { name, text, time, type } = data const item = this.add({ name, text, time, type }) item.classList.add('disable') } // 添加一条消息 add({ name, text, time, type }) { const item = ListItem({ classList: [type], children: [ Span({ innerText: `${name} ${time} ${text}` }) ] }) this.ul.appendChild(item) this.ul.scrollTop = this.ul.scrollHeight return item } // 发送消息 send(text) { if (this.event.onsend) { this.event.onsend(text) } } // 退出 exit() { if (this.event.onexit) { this.event.onexit() } } }