Browse Source

1.编辑框优化

2.修复"请求后发先至"导致的消息乱序问题
3.修复几个小bug
master
xsx 2 years ago
parent
commit
9bf4859e94
  1. 2
      im-commom/src/main/java/com/bx/imcommon/mq/RedisMQPullTask.java
  2. 58
      im-uniapp/pages/chat/chat-box.vue
  3. 6
      im-web/src/components/chat/ChatAtBox.vue
  4. 199
      im-web/src/components/chat/ChatBox.vue
  5. 298
      im-web/src/components/chat/ChatInput.vue
  6. 8
      im-web/src/components/chat/ChatMessageItem.vue
  7. 14
      im-web/src/view/Home.vue

2
im-commom/src/main/java/com/bx/imcommon/mq/RedisMQPullTask.java

@ -53,6 +53,8 @@ public class RedisMQPullTask implements CommandLineRunner {
List<Object> datas = new LinkedList<>(); List<Object> datas = new LinkedList<>();
try { try {
if(redisMQTemplate.isClose()){ if(redisMQTemplate.isClose()){
// 如果redis未初始化或已断开,3s后再重新尝试消费
EXECUTOR.schedule(this, 3, TimeUnit.SECONDS);
return; return;
} }
if (consumer.isReady()) { if (consumer.isReady()) {

58
im-uniapp/pages/chat/chat-box.vue

@ -132,9 +132,10 @@
showRecord: false, showRecord: false,
keyboardHeight: 322, keyboardHeight: 322,
atUserIds: [], atUserIds: [],
recordText: "",
needScrollToBottom: false, // needScrollToBottom: false, //
showMinIdx: 0 // showMinIdx showMinIdx: 0, // showMinIdx
reqQueue: [], //
isSending: false //
} }
}, },
methods: { methods: {
@ -154,11 +155,7 @@
} }
// id // id
this.fillTargetId(msgInfo, this.chat.targetId); this.fillTargetId(msgInfo, this.chat.targetId);
this.$http({ this.sendMessageRequest(msgInfo).then((m) => {
url: this.messageAction,
method: 'POST',
data: msgInfo
}).then((m) => {
m.selfSend = true; m.selfSend = true;
this.$store.commit("insertMessage", m); this.$store.commit("insertMessage", m);
// //
@ -278,19 +275,14 @@
receipt: this.isReceipt, receipt: this.isReceipt,
type: 0 type: 0
} }
this.sendText = "";
// id // id
this.fillTargetId(msgInfo, this.chat.targetId); this.fillTargetId(msgInfo, this.chat.targetId);
this.sendText = ""; this.sendMessageRequest(msgInfo).then((m) => {
this.$http({
url: this.messageAction,
method: 'POST',
data: msgInfo
}).then((m) => {
m.selfSend = true; m.selfSend = true;
this.$store.commit("insertMessage", m); this.$store.commit("insertMessage", m);
// //
this.moveChatToTop(); this.moveChatToTop();
this.sendText = "";
}).finally(() => { }).finally(() => {
// //
this.scrollToBottom(); this.scrollToBottom();
@ -408,11 +400,7 @@
let msgInfo = JSON.parse(JSON.stringify(file.msgInfo)); let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
msgInfo.content = JSON.stringify(res.data); msgInfo.content = JSON.stringify(res.data);
msgInfo.receipt = this.isReceipt msgInfo.receipt = this.isReceipt
this.$http({ this.sendMessageRequest(msgInfo).then((m) => {
url: this.messageAction,
method: 'POST',
data: msgInfo
}).then((m) => {
msgInfo.loadStatus = 'ok'; msgInfo.loadStatus = 'ok';
msgInfo.id = m.id; msgInfo.id = m.id;
this.isReceipt = false; this.isReceipt = false;
@ -463,11 +451,7 @@
let msgInfo = JSON.parse(JSON.stringify(file.msgInfo)); let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
msgInfo.content = JSON.stringify(data); msgInfo.content = JSON.stringify(data);
msgInfo.receipt = this.isReceipt msgInfo.receipt = this.isReceipt
this.$http({ this.sendMessageRequest(msgInfo).then((m) => {
url: this.messageAction,
method: 'POST',
data: msgInfo
}).then((m) => {
msgInfo.loadStatus = 'ok'; msgInfo.loadStatus = 'ok';
msgInfo.id = m.id; msgInfo.id = m.id;
this.isReceipt = false; this.isReceipt = false;
@ -632,6 +616,32 @@
let px = info.windowWidth * rpx / 750; let px = info.windowWidth * rpx / 750;
return Math.floor(rpx); return Math.floor(rpx);
}, },
sendMessageRequest(msgInfo){
return new Promise((resolve,reject)=>{
// ""
this.reqQueue.push({msgInfo,resolve,reject});
this.processReqQueue();
})
},
processReqQueue(){
if (this.reqQueue.length && !this.isSending) {
this.isSending = true;
const reqData = this.reqQueue.shift();
this.$http({
url: this.messageAction,
method: 'post',
data: reqData.msgInfo
}).then((res)=>{
reqData.resolve(res)
}).catch((e)=>{
reqData.reject(e)
}).finally(()=>{
this.isSending = false;
//
this.processReqQueue();
})
}
},
generateId(){ generateId(){
// id // id
return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000)); return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));

6
im-web/src/components/chat/ChatAtBox.vue

@ -1,5 +1,5 @@
<template> <template>
<el-scrollbar v-show="show" ref="scrollBox" class="group-member-choose" <el-scrollbar v-show="show&&showMembers.length" ref="scrollBox" class="group-member-choose"
:style="{'left':pos.x+'px','top':pos.y-300+'px'}"> :style="{'left':pos.x+'px','top':pos.y-300+'px'}">
<div v-for="(member,idx) in showMembers" :key="member.id"> <div v-for="(member,idx) in showMembers" :key="member.id">
<chat-group-member :member="member" :height="40" :active='activeIdx==idx' <chat-group-member :member="member" :height="40" :active='activeIdx==idx'
@ -56,10 +56,6 @@
} }
}) })
this.activeIdx = this.showMembers.length > 0 ? 0: -1; this.activeIdx = this.showMembers.length > 0 ? 0: -1;
console.log(this.showMembers.length)
if(this.showMembers.length == 0){
this.close();
}
}, },
open(pos) { open(pos) {
this.show = true; this.show = true;

199
im-web/src/components/chat/ChatBox.vue

@ -58,21 +58,6 @@
<div title="聊天记录" class="el-icon-chat-dot-round" @click="showHistoryBox()"></div> <div title="聊天记录" class="el-icon-chat-dot-round" @click="showHistoryBox()"></div>
</div> </div>
<div class="send-content-area"> <div class="send-content-area">
<!-- <div contenteditable="true" v-show="!sendImageUrl" ref="editBox" class="send-text-area"-->
<!-- :disabled="lockMessage" @paste.prevent="onEditorPaste"-->
<!-- @compositionstart="onEditorCompositionStart"-->
<!-- @compositionend="onEditorCompositionEnd" @input="onEditorInput"-->
<!-- :placeholder="placeholder" @blur="onEditBoxBlur()" @keydown.down="onKeyDown"-->
<!-- @keydown.up="onKeyUp" @keydown.enter.prevent="onKeyEnter($event)">x-->
<!-- </div>-->
<!-- <div v-show="sendImageUrl" class="send-image-area">-->
<!-- <div class="send-image-box">-->
<!-- <img class="send-image" :src="sendImageUrl" />-->
<!-- <span class="send-image-close el-icon-close" title="删除"-->
<!-- @click="removeSendImage()"></span>-->
<!-- </div>-->
<!-- </div>-->
<ChatInput :ownerId="group.ownerId" ref="chatInputEditor" :group-members="groupMembers" <ChatInput :ownerId="group.ownerId" ref="chatInputEditor" :group-members="groupMembers"
@submit="sendMessage" /> @submit="sendMessage" />
<div class="send-btn-area"> <div class="send-btn-area">
@ -88,8 +73,6 @@
</el-container> </el-container>
</el-main> </el-main>
<emotion ref="emoBox" @emotion="onEmotion"></Emotion> <emotion ref="emoBox" @emotion="onEmotion"></Emotion>
<!-- <chat-at-box ref="atBox" :ownerId="group.ownerId" :members="groupMembers" :search-text="atSearchText"-->
<!-- @select="onAtSelect"></chat-at-box>-->
<chat-record :visible="showRecord" @close="closeRecordBox" @send="onSendRecord"></chat-record> <chat-record :visible="showRecord" @close="closeRecordBox" @send="onSendRecord"></chat-record>
<group-member-selector ref="rtcSel" :groupId="group.id" @complete="onInviteOk"></group-member-selector> <group-member-selector ref="rtcSel" :groupId="group.id" @complete="onInviteOk"></group-member-selector>
<rtc-group-join ref="rtcJoin" :groupId="group.id"></rtc-group-join> <rtc-group-join ref="rtcJoin" :groupId="group.id"></rtc-group-join>
@ -144,11 +127,9 @@ export default {
showSide: false, // showSide: false, //
showHistory: false, // showHistory: false, //
lockMessage: false, // lockMessage: false, //
showMinIdx: 0, // showMinIdx showMinIdx: 0, // showMinIdx
atSearchText: "", reqQueue: [],
focusNode: null, // isSending : false
focusOffset: null, //
zhLock: false //
} }
}, },
methods: { methods: {
@ -171,50 +152,11 @@ export default {
this.isReceipt = !this.isReceipt; this.isReceipt = !this.isReceipt;
this.refreshPlaceHolder(); this.refreshPlaceHolder();
}, },
createSendText() {
let sendText = this.isReceipt ? "【回执消息】" : "";
this.$refs.editBox.childNodes.forEach((node) => {
if (node.nodeName == "#text") {
sendText += this.html2Escape(node.textContent);
} else if (node.nodeName == "SPAN") {
sendText += node.innerHTML;
} else if (node.nodeName == "IMG") {
sendText += node.dataset.code;
}
})
return sendText;
},
html2Escape(strHtml) {
return strHtml.replace(/[<>&"]/g, function (c) {
return {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;'
} [c];
});
},
createAtUserIds(sendContent) {
let ids = [];
let tempEl = document.createElement('div');
tempEl.innerHTML = sendContent;
tempEl.childNodes.forEach((node) => {
if (node.nodeName == "SPAN") {
ids.push(node.dataset.id);
}
})
return ids;
},
onImageSuccess(data, file) { onImageSuccess(data, file) {
let msgInfo = JSON.parse(JSON.stringify(file.msgInfo)); let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
msgInfo.content = JSON.stringify(data); msgInfo.content = JSON.stringify(data);
msgInfo.receipt = this.isReceipt; msgInfo.receipt = this.isReceipt;
this.$http({ this.sendMessageRequest(msgInfo).then((id) => {
url: this.messageAction,
method: 'post',
data: msgInfo
}).then((id) => {
msgInfo.loadStatus = 'ok'; msgInfo.loadStatus = 'ok';
msgInfo.id = id; msgInfo.id = id;
this.isReceipt = false; this.isReceipt = false;
@ -265,11 +207,7 @@ export default {
let msgInfo = JSON.parse(JSON.stringify(file.msgInfo)); let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
msgInfo.content = JSON.stringify(data); msgInfo.content = JSON.stringify(data);
msgInfo.receipt = this.isReceipt msgInfo.receipt = this.isReceipt
this.$http({ this.sendMessageRequest(msgInfo).then((m) => {
url: this.messageAction,
method: 'post',
data: msgInfo
}).then((m) => {
msgInfo.loadStatus = 'ok'; msgInfo.loadStatus = 'ok';
msgInfo.id = m.id; msgInfo.id = m.id;
this.isReceipt = false; this.isReceipt = false;
@ -337,22 +275,7 @@ export default {
}) })
}, },
onEmotion(emoText) { onEmotion(emoText) {
//
// this.$refs.editBox.focus();
// let range = window.getSelection().getRangeAt(0);
// //
// range.setStart(this.focusNode, this.focusOffset)
// let element = document.createElement('IMG')
// element.className = "emo"
// element.dataset.code = emoText;
// element.contentEditable = 'true'
// element.setAttribute("src", this.$emo.textToUrl(emoText));
// //
// range.insertNode(element)
// //
// range.collapse()
this.$refs.chatInputEditor.insertEmoji(emoText); this.$refs.chatInputEditor.insertEmoji(emoText);
}, },
showRecordBox() { showRecordBox() {
this.showRecord = true; this.showRecord = true;
@ -382,7 +305,6 @@ export default {
let ids = [this.mine.id]; let ids = [this.mine.id];
let maxChannel = this.$store.state.configStore.webrtc.maxChannel; let maxChannel = this.$store.state.configStore.webrtc.maxChannel;
this.$refs.rtcSel.open(maxChannel, ids, ids); this.$refs.rtcSel.open(maxChannel, ids, ids);
} }
}) })
@ -424,11 +346,7 @@ export default {
} }
// id // id
this.fillTargetId(msgInfo, this.chat.targetId); this.fillTargetId(msgInfo, this.chat.targetId);
this.$http({ this.sendMessageRequest(msgInfo).then((m) => {
url: this.messageAction,
method: 'post',
data: msgInfo
}).then((m) => {
m.selfSend = true; m.selfSend = true;
this.$store.commit("insertMessage", m); this.$store.commit("insertMessage", m);
// //
@ -441,7 +359,6 @@ export default {
this.showRecord = false; this.showRecord = false;
this.isReceipt = false; this.isReceipt = false;
this.refreshPlaceHolder(); this.refreshPlaceHolder();
}) })
}, },
fillTargetId(msgInfo, targetId) { fillTargetId(msgInfo, targetId) {
@ -454,42 +371,29 @@ export default {
notifySend() { notifySend() {
this.$refs.chatInputEditor.submit(); this.$refs.chatInputEditor.submit();
}, },
sendMessage(fullList) { async sendMessage(fullList) {
// if (this.sendImageFile) { this.resetEditor();
// this.sendImageMessage();
// } else {
// this.sendTextMessage();
// }
// //
// this.readedMessage()
//
// console.log(arguments)
this.readedMessage(); this.readedMessage();
let sendText = this.isReceipt ? "【回执消息】" : ""; let sendText = this.isReceipt ? "【回执消息】" : "";
let promiseList = []; let promiseList = [];
for (let i = 0; i < fullList.length; i++) { for (let i = 0; i < fullList.length; i++) {
let msg = fullList[i]; let msg = fullList[i];
promiseList.push(new Promise(() => {
switch (msg.type) { switch (msg.type) {
case "text": case "text":
this.sendTextMessage(sendText + msg.content); await this.sendTextMessage(sendText + msg.content,msg.atUserIds);
break; break;
case "image": case "image":
this.sendImageMessage(msg.content.file); await this.sendImageMessage(msg.content.file);
break; break;
case "file": case "file":
console.log(msg) await this.sendFileMessage(msg.content.file);
this.sendFileMessage(msg.content.file);
break; break;
} }
}))
} }
Promise.all(promiseList);
// console.log(arguments)
this.$refs.chatInputEditor.clear();
}, },
sendImageMessage(file) { sendImageMessage(file) {
return new Promise((resolve,reject)=>{
this.onImageBefore(file); this.onImageBefore(file);
let formData = new FormData() let formData = new FormData()
formData.append('file', file) formData.append('file', file)
@ -499,15 +403,19 @@ export default {
} }
}).then((data) => { }).then((data) => {
this.onImageSuccess(data, file); this.onImageSuccess(data, file);
resolve();
}).catch((res) => { }).catch((res) => {
this.onImageSuccess(res, file); this.onImageFail(res, file);
reject();
}) })
this.$nextTick(() => this.$refs.chatInputEditor.focus()); this.$nextTick(() => this.$refs.chatInputEditor.focus());
this.scrollToBottom(); this.scrollToBottom();
});
}, },
sendTextMessage(sendText) { sendTextMessage(sendText,atUserIds) {
return new Promise((resolve,reject)=>{
if (!sendText.trim()) { if (!sendText.trim()) {
return reject();
} }
let msgInfo = { let msgInfo = {
content: sendText, content: sendText,
@ -517,34 +425,30 @@ export default {
this.fillTargetId(msgInfo, this.chat.targetId); this.fillTargetId(msgInfo, this.chat.targetId);
// @ // @
if (this.chat.type == "GROUP") { if (this.chat.type == "GROUP") {
msgInfo.atUserIds = this.createAtUserIds(sendText); msgInfo.atUserIds = atUserIds;
msgInfo.receipt = this.isReceipt; msgInfo.receipt = this.isReceipt;
} }
this.lockMessage = true; this.lockMessage = true;
this.$http({ this.sendMessageRequest(msgInfo).then((m) => {
url: this.messageAction,
method: 'post',
data: msgInfo
}).then((m) => {
m.selfSend = true; m.selfSend = true;
this.$store.commit("insertMessage", m); this.$store.commit("insertMessage", m);
// //
this.moveChatToTop(); this.moveChatToTop();
}).finally(() => { }).finally(() => {
// //
this.lockMessage = false;
this.scrollToBottom(); this.scrollToBottom();
this.resetEditor();
this.isReceipt = false; this.isReceipt = false;
resolve();
});
}); });
}, },
sendFileMessage(file) { sendFileMessage(file) {
return new Promise((resolve,reject)=>{
let check = this.$refs.fileUpload.beforeUpload(file); let check = this.$refs.fileUpload.beforeUpload(file);
if (check) { if (check) {
this.$refs.fileUpload.onFileUpload({ file }); this.$refs.fileUpload.onFileUpload({ file });
} }
})
}, },
deleteMessage(msgInfo) { deleteMessage(msgInfo) {
this.$confirm('确认删除消息?', '删除消息', { this.$confirm('确认删除消息?', '删除消息', {
@ -588,8 +492,7 @@ export default {
this.$http({ this.$http({
url: url, url: url,
method: 'put' method: 'put'
}).then(() => { }).then(() => {})
})
}, },
loadReaded(fId) { loadReaded(fId) {
this.$http({ this.$http({
@ -610,7 +513,6 @@ export default {
this.group = group; this.group = group;
this.$store.commit("updateChatFromGroup", group); this.$store.commit("updateChatFromGroup", group);
this.$store.commit("updateGroup", group); this.$store.commit("updateGroup", group);
}); });
this.$http({ this.$http({
@ -651,11 +553,8 @@ export default {
resetEditor() { resetEditor() {
this.$nextTick(() => { this.$nextTick(() => {
// this.$refs.editBox.innerHTML = "";
// this.$refs.editBox.focus();
this.$refs.chatInputEditor.clear(); this.$refs.chatInputEditor.clear();
this.$refs.chatInputEditor.focus(); this.$refs.chatInputEditor.focus();
}); });
}, },
scrollToBottom() { scrollToBottom() {
@ -673,6 +572,32 @@ export default {
this.placeholder = "聊点什么吧~"; this.placeholder = "聊点什么吧~";
} }
}, },
sendMessageRequest(msgInfo){
return new Promise((resolve,reject)=>{
// ""
this.reqQueue.push({msgInfo,resolve,reject});
this.processReqQueue();
})
},
processReqQueue(){
if (this.reqQueue.length && !this.isSending) {
this.isSending = true;
const reqData = this.reqQueue.shift();
this.$http({
url: this.messageAction,
method: 'post',
data: reqData.msgInfo
}).then((res)=>{
reqData.resolve(res)
}).catch((e)=>{
reqData.reject(e)
}).finally(()=>{
this.isSending = false;
//
this.processReqQueue();
})
}
},
generateId() { generateId() {
// id // id
return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000)); return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
@ -702,7 +627,6 @@ export default {
} }
return this.chat.messages.length; return this.chat.messages.length;
} }
}, },
watch: { watch: {
chat: { chat: {
@ -771,7 +695,6 @@ export default {
line-height: 50px; line-height: 50px;
font-size: 25px; font-size: 25px;
cursor: pointer; cursor: pointer;
} }
} }
@ -804,24 +727,27 @@ export default {
box-sizing: border-box; box-sizing: border-box;
border-top: #ccc solid 1px; border-top: #ccc solid 1px;
padding: 2px; padding: 2px;
background-color: #f5f5f5; background-color: #e8f2ff;
>div { >div {
font-size: 22px; font-size: 22px;
cursor: pointer; cursor: pointer;
color: black; color: black;
line-height: 34px; line-height: 30px;
width: 34px; width: 30px;
height: 34px; height: 30px;
text-align: center; text-align: center;
border-radius: 3px; border-radius: 3px;
margin: 3px;
&:hover { &:hover {
color: black; color: black;
} }
&.chat-tool-active { &.chat-tool-active {
background: #ddd; font-weight: 600;
color: #195ee2;
background-color: #ddd;
} }
} }
@ -845,7 +771,6 @@ export default {
resize: none; resize: none;
font-size: 16px; font-size: 16px;
color: black; color: black;
//outline-color: rgba(83, 160, 231, 0.61);
outline: none; outline: none;
text-align: left; text-align: left;
@ -903,7 +828,6 @@ export default {
border: 1px solid #ccc; border: 1px solid #ccc;
} }
} }
} }
.send-btn-area { .send-btn-area {
@ -913,7 +837,6 @@ export default {
right: 0; right: 0;
} }
} }
} }
.chat-group-side-box { .chat-group-side-box {

298
im-web/src/components/chat/ChatInput.vue

@ -1,24 +1,11 @@
<template> <template>
<div class="chat-input-area"> <div class="chat-input-area">
<div :class="['edit-chat-container',isEmpty?'':'not-empty']" contenteditable="true" <div :class="['edit-chat-container',isEmpty?'':'not-empty']" contenteditable="true" @paste.prevent="onPaste"
@paste.prevent="onPaste" @keydown="onKeydown" @compositionstart="compositionFlag=true" @compositionend="onCompositionEnd"
@keydown="onKeydown" @input="onEditorInput" @mousedown="onMousedown" ref="content" @blur="onBlur">
@compositionstart="compositionFlag=true"
@compositionend="compositionFlag=false;updateRange()"
@input="onEditorInput"
@mousedown="onMousedown"
v-html="contentHtml"
ref="content"
@blur="onBlur"
>
</div> </div>
<chat-at-box @select="onAtSelect" <chat-at-box @select="onAtSelect" :search-text="atSearchText" ref="atBox" :ownerId="ownerId"
:search-text="atSearchText" :members="groupMembers"></chat-at-box>
ref="atBox"
:ownerId="ownerId"
:members="groupMembers"
></chat-at-box>
</div> </div>
</template> </template>
@ -31,35 +18,29 @@ export default {
props: { props: {
ownerId: { ownerId: {
type: Number, type: Number,
}, },
groupMembers: { groupMembers: {
type: Array, type: Array,
}, },
}, },
data() { data() {
const defaultContentHtml = '<div></div>';
return { return {
// contentList: [],
// content: null,
defaultContentHtml,
contentHtml: defaultContentHtml + '',
imageList: [], imageList: [],
fileList: [], fileList: [],
currentId: 0, currentId: 0,
atSearchText: null, atSearchText: null,
compositionFlag: false, compositionFlag: false,
history: [defaultContentHtml],
atIng: false, atIng: false,
isEmpty: true, isEmpty: true,
changeStored: true, changeStored: true,
blurRange: null blurRange: null
} }
}, methods: { },
methods: {
onPaste(e) { onPaste(e) {
this.isEmpty = false;
let txt = e.clipboardData.getData('Text') let txt = e.clipboardData.getData('Text')
let range = window.getSelection().getRangeAt(0) let range = window.getSelection().getRangeAt(0)
if (range.startContainer !== range.endContainer || range.startOffset !== range.endOffset) { if (range.startContainer !== range.endContainer || range.startOffset !== range.endOffset) {
range.deleteContents(); range.deleteContents();
} }
@ -67,6 +48,7 @@ export default {
if (txt && typeof(txt) == 'string') { if (txt && typeof(txt) == 'string') {
let textNode = document.createTextNode(txt); let textNode = document.createTextNode(txt);
range.insertNode(textNode) range.insertNode(textNode)
range.collapse();
return; return;
} }
let items = (e.clipboardData || window.clipboardData).items let items = (e.clipboardData || window.clipboardData).items
@ -80,21 +62,15 @@ export default {
url: URL.createObjectURL(file) url: URL.createObjectURL(file)
}; };
this.imageList[imagePush.fileId] = (imagePush); this.imageList[imagePush.fileId] = (imagePush);
let line = this.newLine();
let divElement = this.newLine();
let text = document.createTextNode('\u00A0');
divElement.appendChild(text);
let imageElement = document.createElement('img'); let imageElement = document.createElement('img');
imageElement.className = 'chat-image no-text'; imageElement.className = 'chat-image no-text';
imageElement.src = imagePush.url; imageElement.src = imagePush.url;
imageElement.dataset.imgId = imagePush.fileId; imageElement.dataset.imgId = imagePush.fileId;
line.appendChild(imageElement);
divElement.appendChild(imageElement);
let after = document.createTextNode('\u00A0'); let after = document.createTextNode('\u00A0');
divElement.appendChild(after); line.appendChild(after);
this.selectElement(after, 1); this.selectElement(after, 1);
// range.insertNode(divElement);
} else { } else {
let asFile = items[i].getAsFile(); let asFile = items[i].getAsFile();
if (!asFile) { if (!asFile) {
@ -103,26 +79,20 @@ export default {
let filePush = { fileId: this.generateId(), file: asFile }; let filePush = { fileId: this.generateId(), file: asFile };
this.fileList[filePush.fileId] = (filePush) this.fileList[filePush.fileId] = (filePush)
let line = this.newLine(); let line = this.newLine();
let text = document.createTextNode('\u00A0');
line.appendChild(text);
let fileElement = this.createFile(filePush); let fileElement = this.createFile(filePush);
line.appendChild(fileElement); line.appendChild(fileElement);
let after = document.createTextNode('\u00A0'); let after = document.createTextNode('\u00A0');
line.appendChild(after); line.appendChild(after);
this.selectElement(after, 1); this.selectElement(after, 1);
// fileElement.insertAdjacentHTML('afterend', '\u00A0');
} }
} }
} }
range.collapse(); range.collapse();
}, },
selectElement(element, endOffset) { selectElement(element, endOffset) {
let selection = window.getSelection(); let selection = window.getSelection();
// vuedom // vuedom
setTimeout(() => { this.$nextTick(() => {
let t1 = document.createRange(); let t1 = document.createRange();
t1.setStart(element, 0); t1.setStart(element, 0);
t1.setEnd(element, endOffset || 0); t1.setEnd(element, endOffset || 0);
@ -130,7 +100,6 @@ export default {
t1.selectNodeContents(element.firstChild); t1.selectNodeContents(element.firstChild);
} }
t1.collapse(); t1.collapse();
selection.removeAllRanges(); selection.removeAllRanges();
selection.addRange(t1); selection.addRange(t1);
// //
@ -139,6 +108,10 @@ export default {
} }
}) })
}, },
onCompositionEnd(e) {
this.compositionFlag = false;
this.onEditorInput(e);
},
onKeydown(e) { onKeydown(e) {
if (e.keyCode === 13) { if (e.keyCode === 13) {
e.preventDefault(); e.preventDefault();
@ -148,10 +121,11 @@ export default {
this.$refs.atBox.select(); this.$refs.atBox.select();
return; return;
} }
if (e.shiftKey) { if (e.ctrlKey) {
let divElement = this.newLine(); let line = this.newLine();
let after = document.createTextNode('\u00A0');
this.selectElement(divElement); line.appendChild(after);
this.selectElement(line.childNodes[0], 0);
} else { } else {
// //
if (this.compositionFlag) { if (this.compositionFlag) {
@ -161,42 +135,15 @@ export default {
} }
return; return;
} }
if (e.keyCode === 90) {
// Ctrl+Zmaccommand+z
if (e.ctrlKey || e.metaKey) {
// ctrl+zctrl+zlow
e.preventDefault();
e.stopPropagation();
if (this.history.length <= 1) {
return;
}
if (this.changeStored) {
this.history.pop();
}
let last = this.history.pop();
// console.log('', last);
this.contentHtml = last;
if (this.history.length === 0) {
//
this.history.push(this.defaultContentHtml);
}
// dom
setTimeout(() => {
let t = this.$refs.content.lastElementChild.lastChild;
if (!t || !t.textContent) {
return;
}
this.selectElement(t, t.textContent.length);
})
}
}
// //
if (e.keyCode === 8) { if (e.keyCode === 8) {
console.log("delete")
// dom // dom
setTimeout(() => { setTimeout(() => {
let s = this.$refs.content.innerHTML.trim(); let s = this.$refs.content.innerHTML.trim();
// domdom // domdom
if (s === '' || s === '<br>' || s === '<div><br></div>' || s === '<div><br/></div>') { console.log(s);
if (s === '' || s === '<br>' || s === '<div>&nbsp;</div>' ) {
// dom // dom
this.empty(); this.empty();
this.isEmpty = true; this.isEmpty = true;
@ -219,24 +166,27 @@ export default {
this.$refs.atBox.moveDown(); this.$refs.atBox.moveDown();
} }
} }
}, },
onAtSelect(member) { onAtSelect(member) {
this.atIng = false; this.atIng = false;
// @xx // @xx
let blurRange = this.blurRange; let blurRange = this.blurRange;
let startOffset = blurRange.endOffset - this.atSearchText.length - 1; let endContainer = blurRange.endContainer
let startOffset = endContainer.data.indexOf("@"+this.atSearchText);
let endOffset = startOffset + this.atSearchText.length + 1;
blurRange.setStart(blurRange.endContainer, startOffset); blurRange.setStart(blurRange.endContainer, startOffset);
blurRange.setEnd(blurRange.endContainer, endOffset);
blurRange.deleteContents() blurRange.deleteContents()
blurRange.collapse(); blurRange.collapse();
console.log("onAtSelect")
this.focus(); this.focus();
// //
let element = document.createElement('SPAN') let element = document.createElement('SPAN')
element.className = "chat-at-user"; element.className = "chat-at-user";
element.dataset.id = member.userId; element.dataset.id = member.userId;
element.contentEditable = 'false' element.contentEditable = 'false'
element.innerText = `@${member.aliasName}` element.innerText = `@${member.showNickName}`
blurRange.insertNode(element) blurRange.insertNode(element)
// //
blurRange.collapse() blurRange.collapse()
@ -250,10 +200,8 @@ export default {
this.selectElement(textNode, 1); this.selectElement(textNode, 1);
}, },
onEditorInput(e) { onEditorInput(e) {
// timeoutcompositionend
this.isEmpty = false; this.isEmpty = false;
this.changeStored = false; this.changeStored = false;
setTimeout(() => {
if (this.$props.groupMembers && !this.compositionFlag) { if (this.$props.groupMembers && !this.compositionFlag) {
let selection = window.getSelection() let selection = window.getSelection()
let range = selection.getRangeAt(0); let range = selection.getRangeAt(0);
@ -273,8 +221,7 @@ export default {
this.$refs.atBox.close(); this.$refs.atBox.close();
return; return;
} }
//
this.showAtBox(e)
let endIndex = endOffset; let endIndex = endOffset;
for (let i = endOffset; i < textContent.length; i++) { for (let i = endOffset; i < textContent.length; i++) {
if (textContent[i] === ' ') { if (textContent[i] === ' ') {
@ -283,11 +230,16 @@ export default {
} }
} }
this.atSearchText = textContent.substring(startIndex + 1, endIndex).trim(); this.atSearchText = textContent.substring(startIndex + 1, endIndex).trim();
//
if (this.atSearchText == '') {
this.showAtBox(e)
} }
}) }
}, },
onBlur(e) { onBlur(e) {
this.updateRange(); this.updateRange();
}, },
onMousedown() { onMousedown() {
if (this.atIng) { if (this.atIng) {
@ -337,8 +289,7 @@ export default {
container.appendChild(left); container.appendChild(left);
let icon = document.createElement('div'); let icon = document.createElement('div');
icon.className = 'file-icon'; icon.className = 'el-icon-document';
icon.innerText = '?';
left.appendChild(icon); left.appendChild(icon);
let right = document.createElement('div'); let right = document.createElement('div');
@ -376,24 +327,18 @@ export default {
newLine() { newLine() {
let selection = window.getSelection(); let selection = window.getSelection();
let range = selection.getRangeAt(0); let range = selection.getRangeAt(0);
let divElement = document.createElement('div'); let divElement = document.createElement('div');
let endContainer = range.endContainer; let endContainer = range.endContainer;
let parentElement = endContainer.parentElement; let parentElement = endContainer.parentElement;
if (parentElement.parentElement === this.$refs.content) {
let newText = endContainer.textContent.substring(range.endOffset).trim(); divElement.innerHTML = endContainer.textContent.substring(range.endOffset).trim();
endContainer.textContent = endContainer.textContent.substring(0, range.endOffset); endContainer.textContent = endContainer.textContent.substring(0, range.endOffset);
divElement.innerHTML = newText || '';
// atparentbug
if (parentElement === this.$refs.content) {
this.$refs.content.append(divElement);
} else {
// div // div
parentElement.insertAdjacentElement('afterend', divElement); parentElement.insertAdjacentElement('afterend', divElement);
} else {
divElement.innerHTML = '';
this.$refs.content.append(divElement);
} }
this.isEmpty = false;
return divElement; return divElement;
}, },
clear() { clear() {
@ -402,12 +347,11 @@ export default {
this.fileList = []; this.fileList = [];
}, },
empty() { empty() {
let emptyCount = Math.random() * 100 + 5; this.$refs.content.innerHTML = "";
let content = ''; let line = this.newLine();
for (let i = 0; i < emptyCount; i++) { let after = document.createTextNode('\u00A0');
content += ' '; line.appendChild(after);
} this.$nextTick(()=>this.selectElement(after));
this.contentHtml = this.defaultContentHtml + content;
}, },
showAtBox(e) { showAtBox(e) {
this.atIng = true; this.atIng = true;
@ -424,17 +368,21 @@ export default {
// //
this.updateRange(); this.updateRange();
}, },
html2Escape(strHtml) {
return strHtml.replace(/[<>&"]/g, function(c) {
return {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;'
} [c];
});
},
submit() { submit() {
// console.log(this.content)
let nodes = this.$refs.content.childNodes; let nodes = this.$refs.content.childNodes;
let textList = [];
let imageList = [];
let fileList = [];
let fullList = []; let fullList = [];
let tempText = ''; let tempText = '';
let atUserIds = [];
let each = (nodes) => { let each = (nodes) => {
for (let i = 0; i < nodes.length; i++) { for (let i = 0; i < nodes.length; i++) {
let node = nodes[i]; let node = nodes[i];
@ -442,7 +390,7 @@ export default {
continue; continue;
} }
if (node.nodeType === 3) { if (node.nodeType === 3) {
tempText += node.textContent; tempText += this.html2Escape(node.textContent);
continue; continue;
} }
let nodeName = node.nodeName.toLowerCase(); let nodeName = node.nodeName.toLowerCase();
@ -456,16 +404,16 @@ export default {
if (text) { if (text) {
fullList.push({ fullList.push({
type: 'text', type: 'text',
content: text content: text,
atUserIds: atUserIds
}) })
tempText = '';
atUserIds = []
} }
fullList.push({ fullList.push({
type: 'image', type: 'image',
content: this.imageList[imgId] content: this.imageList[imgId]
}) })
imageList.push(this.imageList[imgId]);
textList.push(text);
tempText = '';
} else { } else {
let emojiCode = node.dataset.emojiCode; let emojiCode = node.dataset.emojiCode;
tempText += emojiCode; tempText += emojiCode;
@ -477,33 +425,27 @@ export default {
if (text) { if (text) {
fullList.push({ fullList.push({
type: 'text', type: 'text',
content: text content: text,
atUserIds: atUserIds
}) })
tempText = '';
atUserIds = []
} }
fullList.push({ fullList.push({
type: 'file', type: 'file',
content: this.fileList[fileId] content: this.fileList[fileId]
}) })
fileList.push(this.fileList[fileId]);
textList.push(text);
tempText = '';
} else { } else {
tempText += '\n'; tempText += '\n';
each(node.childNodes); each(node.childNodes);
} }
} else if (nodeName === 'span') { } else if (nodeName === 'span') {
let userId = node.dataset.id; if(node.dataset.id){
if (userId !== null && userId !== undefined) { tempText += node.innerHTML;
tempText += node.outerHTML; atUserIds.push(node.dataset.id)
}
} else {
console.warn('未处理的标签');
if (getComputedStyle(node).display === 'block') {
tempText += '\n';
}else { }else {
tempText += ' '; tempText += node.outerHtml;
} }
each(node.childNodes);
} }
} }
} }
@ -512,38 +454,16 @@ export default {
if (text !== '') { if (text !== '') {
fullList.push({ fullList.push({
type: 'text', type: 'text',
content: text content: text,
atUserIds: atUserIds
}) })
textList.push(text);
} }
// console.log(textList, imageList, fileList) this.$emit('submit', fullList);
this.$emit('submit', fullList, textList, imageList, fileList);
}, },
focus() { focus() {
this.$refs.content.focus(); this.$refs.content.focus();
} }
},
mounted() {
// console.log(this.$props.groupMembers)
// this.$refs.content.firstElementChild.focus();
this.selectElement(this.$refs.content.firstElementChild);
setInterval(() => {
if (!this.$refs.content) {
return;
}
//
if (this.compositionFlag) {
return;
}
let last = this.history[this.history.length - 1];
let newContent = this.$refs.content.innerHTML;
if (last !== newContent) {
this.history.push(newContent);
}
this.changeStored = true;
}, 1000);
} }
} }
</script> </script>
@ -555,8 +475,6 @@ export default {
position: relative; position: relative;
.edit-chat-container { .edit-chat-container {
//width: 100%;
//height: 100%;
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
@ -564,16 +482,11 @@ export default {
bottom: 0; bottom: 0;
border: 1px solid #c3c3c3; border: 1px solid #c3c3c3;
outline: none; outline: none;
padding: 10px 0; padding: 5px;
line-height: 30px; line-height: 30px;
font-size: 16px; font-size: 16px;
text-align: left; text-align: left;
overflow-y: scroll;
> div {
padding-left: 10px;
//width: 1px;
min-height: 30px;
}
// bug // bug
>div:before { >div:before {
@ -585,11 +498,11 @@ export default {
} }
.chat-image { .chat-image {
display: block;
max-width: 200px; max-width: 200px;
max-height: 100px; max-height: 100px;
border: 1px solid #e6e6e6; border: 1px solid #e6e6e6;
cursor: pointer; cursor: pointer;
//margin-left: 10px;
} }
.chat-emoji { .chat-emoji {
@ -600,63 +513,56 @@ export default {
} }
.chat-file-container { .chat-file-container {
width: 200px; max-width: 65%;
//height: 100px; padding: 10px;
padding: 5px 7px; border: 2px solid #587ff0;
border: 1px solid #4cd964;
display: flex; display: flex;
background: #eeeC;
border-radius: 10px;
.file-position-left { .file-position-left {
width: 30%; display: flex;
flex: 1; width: 80px;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
.file-icon { .el-icon-document {
width: 30px; font-size: 40px;
height: 30px;
text-align: center; text-align: center;
justify-content: center; color: #d42e07;
align-items: center;
vertical-align: center;
border: 1px solid #e6e6e6;
} }
} }
.file-position-right { .file-position-right {
width: 70%; flex: 1;
flex: 3;
.file-name { .file-name {
font-size: 14px; font-size: 16px;
color: #333; font-weight: 600;
color: #66b1ff;
} }
.file-size { .file-size {
font-size: 12px; font-size: 14px;
color: #666; font-weight: 600;
color: black;
} }
} }
} }
.chat-at-user { .chat-at-user {
background-color: #4cd964; color: #00f;
padding: 2px 5px; font-weight: 600;
color: white;
//border: 1px solid #c3c3c3;
border-radius: 3px; border-radius: 3px;
} }
} }
.edit-chat-container > div:nth-of-type(1):empty:after { .edit-chat-container>div:nth-of-type(1):after {
content: '请输入消息(按Shift+Enter键换行)'; content: '请输入消息(按Ctrl+Enter键换行)';
color: gray; color: gray;
} }
.edit-chat-container > div:nth-of-type(1):focus:after {
content: none;
}
.edit-chat-container.not-empty>div:nth-of-type(1):after { .edit-chat-container.not-empty>div:nth-of-type(1):after {
content: none; content: none;
} }

8
im-web/src/components/chat/ChatMessageItem.vue

@ -67,10 +67,8 @@
<span v-if="msgInfo.receiptOk" class="icon iconfont icon-ok" title="全体已读"></span> <span v-if="msgInfo.receiptOk" class="icon iconfont icon-ok" title="全体已读"></span>
<span v-else>{{msgInfo.readedCount}}人已读</span> <span v-else>{{msgInfo.readedCount}}人已读</span>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<right-menu v-show="menu && rightMenu.show" :pos="rightMenu.pos" :items="menuItems" <right-menu v-show="menu && rightMenu.show" :pos="rightMenu.pos" :items="menuItems"
@close="rightMenu.show = false" @select="onSelectMenu"></right-menu> @close="rightMenu.show = false" @select="onSelectMenu"></right-menu>
@ -129,7 +127,6 @@
} }
} }
} }
}, },
methods: { methods: {
onSendFail() { onSendFail() {
@ -410,11 +407,10 @@
} }
.chat-at-user { .chat-at-user {
background-color: #4cd964;
padding: 2px 5px; padding: 2px 5px;
color: white;
//border: 1px solid #c3c3c3;
border-radius: 3px; border-radius: 3px;
font-weight: 600;
cursor: pointer;
} }
} }
} }

14
im-web/src/view/Home.vue

@ -126,16 +126,22 @@
}) })
}, },
pullPrivateOfflineMessage(minId) { pullPrivateOfflineMessage(minId) {
this.$store.commit("loadingPrivateMsg", true)
this.$http({ this.$http({
url: "/message/private/pullOfflineMessage?minId=" + minId, url: "/message/private/pullOfflineMessage?minId=" + minId,
method: 'get' method: 'GET'
}); }).catch(() => {
this.$store.commit("loadingPrivateMsg", false)
})
}, },
pullGroupOfflineMessage(minId) { pullGroupOfflineMessage(minId) {
this.$store.commit("loadingGroupMsg", true)
this.$http({ this.$http({
url: "/message/group/pullOfflineMessage?minId=" + minId, url: "/message/group/pullOfflineMessage?minId=" + minId,
method: 'get' method: 'GET'
}); }).catch(() => {
this.$store.commit("loadingGroupMsg", false)
})
}, },
handlePrivateMessage(msg) { handlePrivateMessage(msg) {
// //

Loading…
Cancel
Save