This commit is contained in:
2023-10-20 15:13:39 +08:00
parent 692ae68433
commit ef3f17e7a0
2 changed files with 19 additions and 3 deletions

View File

@ -8,6 +8,9 @@ export default class Chat {
this.EventListeners = EventListeners this.EventListeners = EventListeners
document.body.appendChild(this.ul) // 元素加入页面 document.body.appendChild(this.ul) // 元素加入页面
// 使用一个有序列表来存储消息
const messageBox = new Map()
// 添加输入框 // 添加输入框
const input = createElement({ const input = createElement({
type: 'text', type: 'text',
@ -55,15 +58,23 @@ export default class Chat {
` `
document.head.appendChild(style) 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 }) { add({ name, text, time, type }) {
this.ul.appendChild(ListItem({ const item = ListItem({
classList: [type], classList: [type],
children: [ children: [
Span({ innerText: `${name} ${time} ${text}` }) Span({ innerText: `${name} ${time} ${text}` })
] ]
})) })
this.ul.appendChild(item)
this.ul.scrollTop = this.ul.scrollHeight this.ul.scrollTop = this.ul.scrollHeight
return item
} }
// 发送消息 // 发送消息
send(text) { send(text) {

View File

@ -146,8 +146,8 @@ const musicList = new MusicList({
const chat = new Chat({ const chat = new Chat({
onsend: async (text, list) => { onsend: async (text, list) => {
console.log('发送消息', text) console.log('发送消息', text)
clientList.send('chat', JSON.stringify({ type: 'message', text }))
chat.add({ name, text, time: new Date().toLocaleTimeString() }) chat.add({ name, text, time: new Date().toLocaleTimeString() })
clientList.send('chat', JSON.stringify({ type: 'message', text }))
console.log('发送结束') console.log('发送结束')
}, },
onexit: async () => { onexit: async () => {
@ -171,6 +171,11 @@ clientList.setChannel('chat', {
console.log(client.name, '发来图片:', data) console.log(client.name, '发来图片:', data)
return return
} }
if (data.type === 'answer') {
console.log(client.name, '发来应答:', data)
chat.answer(data)
return
}
console.log('未知类型:', data.type) console.log('未知类型:', data.type)
}, },
onclose: event => { onclose: event => {