chat-pc/src/components/editor/CustomEditor.vue

1587 lines
51 KiB
Vue
Raw Normal View History

2025-06-05 08:21:39 +00:00
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick, markRaw, watch } from 'vue'
2025-06-05 08:21:39 +00:00
import { NPopover, NIcon } from 'naive-ui'
import {
2025-06-24 08:27:00 +00:00
SmilingFace,
Pic,
FolderUpload
2025-06-05 08:21:39 +00:00
} from '@icon-park/vue-next'
2025-06-24 08:27:00 +00:00
import {IosSend} from '@vicons/ionicons4'
import { bus } from '@/utils/event-bus'
import { EditorConst } from '@/constant/event-bus'
import { emitCall } from '@/utils/common'
import { deltaToMessage, deltaToString, isEmptyDelta } from './util'
import { uploadImg } from '@/api/upload'
import { defAvatar } from '@/constant/default'
import { getImageInfo } from '@/utils/functions'
import { useDialogueStore, useEditorDraftStore, useUserStore } from '@/store'
import MeEditorEmoticon from './MeEditorEmoticon.vue'
2025-06-05 08:21:39 +00:00
const props = defineProps({
vote: {
type: Boolean,
default: false,
2025-06-05 08:21:39 +00:00
},
members: {
type: Array,
default: () => [],
},
placeholder: {
type: String,
default: 'Enter-发送消息 [Ctrl+Enter/Shift+Enter]-换行',
2025-06-05 08:21:39 +00:00
}
})
const emit = defineEmits(['editor-event'])
2025-06-24 08:27:00 +00:00
const userStore = useUserStore()
const dialogueStore = useDialogueStore()
console.log('dialogueStore',dialogueStore.talk.talk_type)
2025-06-24 08:27:00 +00:00
const editorDraftStore = useEditorDraftStore()
const editorRef = ref(null)
const content = ref('')
const editorContent = ref('')
const editorHtml = ref('')
const isFocused = ref(false)
const showMention = ref(false)
const mentionQuery = ref('')
const mentionPosition = ref({ top: 0, left: 0 })
const selectedMentionIndex = ref(0)
const mentionList = ref([])
const currentMentionQuery = ref('')
const quoteData = ref(null)
const editingMessage = ref(null)
const isShowEmoticon = ref(false)
const fileImageRef = ref(null)
const uploadFileRef = ref(null)
const emoticonRef = ref(null)
const indexName = computed(() => dialogueStore.index_name)
const navs = ref([
2025-06-05 08:21:39 +00:00
{
2025-06-24 08:27:00 +00:00
title: '图片',
icon: markRaw(Pic),
show: true,
2025-06-05 08:21:39 +00:00
click: () => {
fileImageRef.value.click()
}
},
{
2025-06-24 08:27:00 +00:00
title: '文件',
icon: markRaw(FolderUpload),
show: true,
2025-06-05 08:21:39 +00:00
click: () => {
uploadFileRef.value.click()
}
}
])
const toolbarConfig = computed(() => {
const config = [
2025-06-24 08:27:00 +00:00
{ type: 'emoticon', icon: 'icon-biaoqing', title: '表情' },
{ type: 'image', icon: 'icon-image', title: '图片' },
{ type: 'file', icon: 'icon-folder-plus', title: '文件' }
2025-06-05 08:21:39 +00:00
]
return config
})
const handleInput = (event) => {
2025-06-24 08:27:00 +00:00
const editorNode = (event && event.target) ? event.target : editorRef.value;
2025-06-11 08:54:54 +00:00
if (!editorNode) {
return;
}
const target = editorNode;
2025-06-11 08:54:54 +00:00
const editorClone = editorNode.cloneNode(true);
editorClone.querySelectorAll('.editor-quote').forEach(quote => quote.remove());
let rawTextContent = editorClone.textContent || '';
2025-06-11 08:54:54 +00:00
const emojiImages = editorClone.querySelectorAll('img.editor-emoji');
if (emojiImages.length > 0) {
emojiImages.forEach(emoji => {
2025-06-11 08:54:54 +00:00
const altText = emoji.getAttribute('alt');
if (altText) {
rawTextContent += altText;
}
2025-06-11 08:54:54 +00:00
});
}
2025-06-11 08:54:54 +00:00
editorContent.value = rawTextContent;
const currentText = editorNode.textContent.trim();
const hasSpecialElements = editorNode.querySelector('img, .editor-file, .mention');
if (currentText === '' && !hasSpecialElements) {
if (editorNode.innerHTML !== '') {
2025-06-11 08:54:54 +00:00
editorNode.innerHTML = '';
}
}
2025-06-11 08:54:54 +00:00
editorHtml.value = editorNode.innerHTML || '';
const currentEditorItems = parseEditorContent().items;
2025-06-11 08:54:54 +00:00
checkMention(target);
saveDraft();
2025-06-05 08:21:39 +00:00
emit('editor-event', {
event: 'input_event',
2025-06-11 08:54:54 +00:00
data: currentEditorItems.reduce((result, item) => {
if (item.type === 1) return result + item.content;
if (item.type === 3) return result + '[图片]';
return result;
2025-06-11 08:54:54 +00:00
}, '')
});
};
2025-06-05 08:21:39 +00:00
const checkMention = (target) => {
if (dialogueStore.talk.talk_type !== 2) {
hideMentionList()
return
}
2025-06-05 08:21:39 +00:00
const selection = window.getSelection()
if (!selection.rangeCount) return
const range = selection.getRangeAt(0)
const textBeforeCursor = range.startContainer.textContent?.substring(0, range.startOffset) || ''
const mentionMatch = textBeforeCursor.match(/@([^@\s]*)$/)
if (mentionMatch) {
currentMentionQuery.value = mentionMatch[1]
showMentionList()
updateMentionPosition(range)
} else {
hideMentionList()
}
}
const showMentionList = () => {
const query = currentMentionQuery.value.toLowerCase()
mentionList.value = [{ id: 0, nickname: '全体成员', avatar: defAvatar, value: '全体成员' },...props.members].filter(member => {
return member.value.toLowerCase().startsWith(query) && member.id !== userStore.uid
})
2025-06-05 08:21:39 +00:00
showMention.value = mentionList.value.length > 0
selectedMentionIndex.value = 0
}
const handleMentionSelectByMouse = (member) => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
insertMention(member, selection.getRangeAt(0).cloneRange());
} else {
editorRef.value?.focus();
nextTick(() => {
const newSelection = window.getSelection();
if (newSelection && newSelection.rangeCount > 0) {
insertMention(member, newSelection.getRangeAt(0).cloneRange());
}
});
}
};
2025-06-05 08:21:39 +00:00
const hideMentionList = () => {
showMention.value = false
mentionList.value = []
currentMentionQuery.value = ''
}
const updateMentionPosition = (range) => {
const rect = range.getBoundingClientRect()
const editorRect = editorRef.value.getBoundingClientRect()
mentionPosition.value = {
top: rect.bottom - editorRect.top + 5,
left: rect.left - editorRect.left
}
}
const insertMention = (member, clonedRange) => {
console.log('插入mention', member);
const selection = window.getSelection();
2025-06-11 08:54:54 +00:00
if (!clonedRange || !selection || !editorRef.value) return;
const range = clonedRange;
const editor = editorRef.value;
const textNode = range.startContainer;
const offset = range.startOffset;
const textContent = textNode.nodeType === Node.TEXT_NODE ? textNode.textContent || '' : '';
const atIndex = (textNode.nodeType === Node.TEXT_NODE && offset > 0) ? textContent.lastIndexOf('@', offset - 1) : -1;
const mentionSpan = document.createElement('span');
mentionSpan.className = 'mention';
mentionSpan.setAttribute('data-user-id', String(member.id));
2025-06-11 08:54:54 +00:00
mentionSpan.textContent = `@${member.value || member.nickname} `;
2025-06-24 08:27:00 +00:00
mentionSpan.contentEditable = 'false';
if (atIndex !== -1 && textNode.nodeType === Node.TEXT_NODE) {
const parent = textNode.parentNode;
2025-06-11 08:54:54 +00:00
if (!parent) return;
range.setStart(textNode, atIndex);
range.setEnd(textNode, offset);
2025-06-24 08:27:00 +00:00
range.deleteContents();
range.insertNode(mentionSpan);
} else {
if (!range.collapsed) {
2025-06-24 08:27:00 +00:00
range.deleteContents();
}
range.insertNode(mentionSpan);
}
range.setStartAfter(mentionSpan);
2025-06-11 08:54:54 +00:00
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
2025-06-11 08:54:54 +00:00
editor.focus();
nextTick(() => {
2025-06-11 08:54:54 +00:00
handleInput({ target: editor });
hideMentionList();
});
};
2025-06-05 08:21:39 +00:00
const handlePaste = (event) => {
2025-06-11 08:54:54 +00:00
event.preventDefault();
if (!editorRef.value) return;
const clipboardData = event.clipboardData;
if (!clipboardData) return;
const items = clipboardData.items;
let imagePasted = false;
if (items) {
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
2025-06-11 08:54:54 +00:00
const file = items[i].getAsFile();
if (file) {
2025-06-11 08:54:54 +00:00
imagePasted = true;
const tempUrl = URL.createObjectURL(file);
2025-06-11 08:54:54 +00:00
const image = new Image();
image.src = tempUrl;
image.onload = () => {
const form = new FormData();
2025-06-11 08:54:54 +00:00
form.append('file', file);
form.append('source', 'fonchain-chat');
form.append('urlParam', `width=${image.width}&height=${image.height}`);
const insertedImgElement = insertImage(tempUrl, image.width, image.height);
if (insertedImgElement && insertedImgElement.parentNode) {
insertedImgElement.parentNode.classList.add('image-upload-loading');
}
2025-06-11 08:54:54 +00:00
uploadImg(form).then(({ code, data, message }) => {
const currentEditorImages = editorRef.value.querySelectorAll('img.editor-image');
2025-06-11 08:54:54 +00:00
if (code === 0 && data && data.ori_url) {
for (let j = currentEditorImages.length - 1; j >= 0; j--) {
if (currentEditorImages[j].src === tempUrl) {
currentEditorImages[j].src = data.ori_url;
if (currentEditorImages[j].parentNode) {
currentEditorImages[j].parentNode.classList.remove('image-upload-loading');
}
break;
2025-06-11 08:54:54 +00:00
}
}
handleInput({ target: editorRef.value });
} else {
2025-06-11 08:54:54 +00:00
window['$message'].error(message || '图片上传失败');
for (let j = currentEditorImages.length - 1; j >= 0; j--) {
if (currentEditorImages[j].src === tempUrl) {
if (currentEditorImages[j].parentNode) {
2025-06-24 08:27:00 +00:00
currentEditorImages[j].parentNode.remove();
} else {
2025-06-24 08:27:00 +00:00
currentEditorImages[j].remove();
}
2025-06-11 08:54:54 +00:00
break;
}
}
handleInput({ target: editorRef.value });
}
2025-06-24 08:27:00 +00:00
URL.revokeObjectURL(tempUrl);
2025-06-11 08:54:54 +00:00
}).catch(error => {
console.error('Upload image error:', error);
window['$message'].error('图片上传过程中发生错误');
const currentEditorImages = editorRef.value.querySelectorAll('img.editor-image');
for (let j = currentEditorImages.length - 1; j >= 0; j--) {
if (currentEditorImages[j].src === tempUrl) {
if (currentEditorImages[j].parentNode) {
2025-06-24 08:27:00 +00:00
currentEditorImages[j].parentNode.remove();
} else {
2025-06-24 08:27:00 +00:00
currentEditorImages[j].remove();
2025-06-11 08:54:54 +00:00
}
break;
2025-06-11 08:54:54 +00:00
}
}
2025-06-11 08:54:54 +00:00
handleInput({ target: editorRef.value });
2025-06-24 08:27:00 +00:00
URL.revokeObjectURL(tempUrl);
2025-06-11 08:54:54 +00:00
});
};
image.onerror = () => {
URL.revokeObjectURL(tempUrl);
window['$message'].error('无法加载粘贴的图片');
};
2025-06-24 08:27:00 +00:00
return;
}
}
}
}
if (!imagePasted) {
2025-06-11 08:54:54 +00:00
const text = clipboardData.getData('text/plain') || '';
if (text) {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
range.deleteContents();
const textNode = document.createTextNode(text);
range.insertNode(textNode);
range.setStartAfter(textNode);
2025-06-11 08:54:54 +00:00
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
handleInput({ target: editorRef.value });
}
2025-06-05 08:21:39 +00:00
}
}
2025-06-11 08:54:54 +00:00
};
const insertLineBreak = (range) => {
const editor = editorRef.value;
if (!editor) return;
const br = document.createElement('br');
range.deleteContents();
range.insertNode(br);
const nbsp = document.createTextNode('\u200B');
range.setStartAfter(br);
range.insertNode(nbsp);
range.setStartAfter(nbsp);
range.collapse(true);
const selection = window.getSelection();
if (selection) {
selection.removeAllRanges();
selection.addRange(range);
}
editor.focus();
nextTick(() => {
handleInput({ target: editor });
});
};
2025-06-05 08:21:39 +00:00
const handleKeydown = (event) => {
2025-06-11 08:54:54 +00:00
const editor = editorRef.value;
if (!editor) return;
if (showMention.value) {
2025-06-11 08:54:54 +00:00
const mentionUl = document.querySelector('.mention-list ul');
let handled = false;
2025-06-05 08:21:39 +00:00
switch (event.key) {
case 'ArrowUp':
2025-06-11 08:54:54 +00:00
selectedMentionIndex.value = Math.max(0, selectedMentionIndex.value - 1);
if (mentionUl) {
const selectedItem = mentionUl.children[selectedMentionIndex.value];
if (selectedItem && selectedItem.offsetTop < mentionUl.scrollTop) {
mentionUl.scrollTop = selectedItem.offsetTop;
}
2025-06-11 08:54:54 +00:00
}
handled = true;
break;
2025-06-05 08:21:39 +00:00
case 'ArrowDown':
2025-06-11 08:54:54 +00:00
selectedMentionIndex.value = Math.min(mentionList.value.length - 1, selectedMentionIndex.value + 1);
if (mentionUl) {
const selectedItem = mentionUl.children[selectedMentionIndex.value];
if (selectedItem) {
const itemBottom = selectedItem.offsetTop + selectedItem.offsetHeight;
const listBottom = mentionUl.scrollTop + mentionUl.clientHeight;
if (itemBottom > listBottom) {
2025-06-11 08:54:54 +00:00
mentionUl.scrollTop = itemBottom - mentionUl.clientHeight;
}
}
2025-06-11 08:54:54 +00:00
}
handled = true;
break;
2025-06-05 08:21:39 +00:00
case 'Enter':
case 'Tab':
const selectedMember = mentionList.value[selectedMentionIndex.value];
if (selectedMember) {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
insertMention(selectedMember, selection.getRangeAt(0).cloneRange());
}
2025-06-05 08:21:39 +00:00
}
2025-06-11 08:54:54 +00:00
handled = true;
break;
2025-06-05 08:21:39 +00:00
case 'Escape':
2025-06-11 08:54:54 +00:00
hideMentionList();
handled = true;
break;
}
if (handled) {
event.preventDefault();
return;
2025-06-05 08:21:39 +00:00
}
}
if (event.key === 'Backspace' || event.key === 'Delete') {
2025-06-11 08:54:54 +00:00
const selection = window.getSelection();
if (!selection || !selection.rangeCount) return;
const range = selection.getRangeAt(0);
if (range.collapsed) {
2025-06-11 08:54:54 +00:00
let nodeToCheck = null;
let positionRelativeToCheck = '';
2025-06-11 08:54:54 +00:00
const container = range.startContainer;
const offset = range.startOffset;
if (event.key === 'Backspace') {
if (offset === 0) {
nodeToCheck = container.previousSibling;
2025-06-11 08:54:54 +00:00
positionRelativeToCheck = 'before';
} else if (container.nodeType === Node.ELEMENT_NODE && offset > 0) {
nodeToCheck = container.childNodes[offset - 1];
2025-06-11 08:54:54 +00:00
positionRelativeToCheck = 'before';
}
} else if (event.key === 'Delete') {
if (container.nodeType === Node.TEXT_NODE && offset === container.textContent.length) {
nodeToCheck = container.nextSibling;
2025-06-11 08:54:54 +00:00
positionRelativeToCheck = 'after';
} else if (container.nodeType === Node.ELEMENT_NODE && offset < container.childNodes.length) {
nodeToCheck = container.childNodes[offset];
2025-06-11 08:54:54 +00:00
positionRelativeToCheck = 'after';
}
}
if (nodeToCheck && nodeToCheck.nodeType === Node.ELEMENT_NODE && nodeToCheck.classList.contains('mention')) {
2025-06-24 08:27:00 +00:00
event.preventDefault();
2025-06-11 08:54:54 +00:00
const parent = nodeToCheck.parentNode;
2025-06-24 08:27:00 +00:00
parent.removeChild(nodeToCheck);
2025-06-11 08:54:54 +00:00
handleInput({ target: editor });
return;
}
}
}
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey || event.shiftKey)) {
2025-06-24 08:27:00 +00:00
event.preventDefault();
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) {
editor.focus();
nextTick(() => {
const newSelection = window.getSelection();
if (newSelection && newSelection.rangeCount > 0) {
insertLineBreak(newSelection.getRangeAt(0));
}
});
return;
}
insertLineBreak(selection.getRangeAt(0));
return;
}
if (event.key === 'Enter' && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
2025-06-24 08:27:00 +00:00
event.preventDefault();
2025-06-11 08:54:54 +00:00
const messageData = parseEditorContent();
const isEmptyMessage = messageData.items.length === 0 ||
2025-06-11 08:54:54 +00:00
(messageData.items.length === 1 &&
messageData.items[0].type === 1 &&
!messageData.items[0].content.trimEnd());
if (isEmptyMessage) {
2025-06-11 08:54:54 +00:00
if (editor.innerHTML.trim() !== '' && editor.innerHTML.trim() !== '<br>') {
clearEditor();
}
2025-06-11 08:54:54 +00:00
return;
}
const quoteElement = editor.querySelector('.editor-quote');
if (!quoteElement && quoteData.value) {
quoteData.value = null;
2025-06-05 08:21:39 +00:00
}
2025-06-11 08:54:54 +00:00
sendMessage();
2025-06-05 08:21:39 +00:00
}
2025-06-11 08:54:54 +00:00
};
2025-06-05 08:21:39 +00:00
const sendMessage = () => {
2025-06-11 08:54:54 +00:00
const editor = editorRef.value;
if (!editor) return;
const parsedData = parseEditorContent();
const cleanInvisibleChars = (text) => {
return text ? String(text).replace(/[\u200B-\u200D\uFEFF]/g, '') : '';
};
let finalItems = [];
if (parsedData && parsedData.items) {
finalItems = parsedData.items.map(item => {
if (item.type === 1 && typeof item.content === 'string') {
let content = cleanInvisibleChars(item.content);
2025-06-11 08:54:54 +00:00
content = content.replace(/<br\s*\/?>/gi, '\n').trim();
return { ...item, content };
}
2025-06-11 08:54:54 +00:00
return item;
}).filter(item => {
if (item.type === 1 && !item.content && !(parsedData.mentionUids && parsedData.mentionUids.length > 0)) return false;
if (item.type === 3 && !item.content) return false;
if (item.type === 4 && !item.content) return false;
return true;
2025-06-11 08:54:54 +00:00
});
}
const hasActualContent = finalItems.some(item => (item.type === 1 && item.content) || item.type === 3 || item.type === 4);
if (!hasActualContent && !(parsedData.mentionUids && parsedData.mentionUids.length > 0) && !parsedData.quoteId) {
if (editor.innerHTML.trim() !== '' && editor.innerHTML.trim() !== '<br>') {
clearEditor();
}
2025-06-11 08:54:54 +00:00
return;
}
const messageToSend = {
items: finalItems.length > 0 ? finalItems : [{ type: 1, content: '' }],
mentionUids: parsedData.mentionUids || [],
mentions: (parsedData.mentionUids || []).map(uid => {
const member = mentionList.value.find(m => m.id === uid);
return { atid: uid, name: member ? member.nickname : '' };
}),
quoteId: parsedData.quoteId || null
};
if (messageToSend.quoteId && quoteData.value && quoteData.value.id === messageToSend.quoteId) {
messageToSend.quote = { ...quoteData.value };
} else if (messageToSend.quoteId) {
} else {
delete messageToSend.quote;
2025-06-11 08:54:54 +00:00
}
messageToSend.items.forEach(item => {
if (item.type === 1 && cleanInvisibleChars(item.content.trimEnd())) {
const data = {
items: [{
content: cleanInvisibleChars(item.content),
type: 1
}],
mentionUids: messageToSend.mentionUids,
mentions: messageToSend.mentionUids.map(uid => {
return {
atid: uid,
name: mentionList.value.find(member => member.id === uid)?.nickname || ''
}
}),
quoteId: messageToSend.quoteId,
}
emit(
'editor-event',
emitCall('text_event', data)
)
} else if (item.type === 3) {
const data = {
height: 0,
width: 0,
size: 10000,
url: item.content,
}
emit(
'editor-event',
emitCall('image_event', data)
)
} else if (item.type === 4) {
}
})
2025-06-11 08:54:54 +00:00
clearEditor();
2025-06-05 08:21:39 +00:00
}
const parseEditorContent = () => {
2025-06-11 08:54:54 +00:00
const items = [];
const mentionUids = new Set();
let parsedQuoteId = null;
const editorNode = editorRef.value;
if (!editorNode) {
return { items: [{ type: 1, content: '' }], mentionUids: [], quoteId: null };
}
const tempDiv = document.createElement('div');
tempDiv.innerHTML = editorHtml.value;
2025-06-11 08:54:54 +00:00
const quoteElement = tempDiv.querySelector('.editor-quote');
if (quoteElement && quoteData.value && quoteData.value.id) {
parsedQuoteId = quoteData.value.id;
quoteElement.remove();
2025-06-11 08:54:54 +00:00
}
let currentTextBuffer = '';
const flushTextBufferIfNeeded = () => {
if (currentTextBuffer) {
items.push({ type: 1, content: currentTextBuffer });
}
currentTextBuffer = '';
};
const processNodeRecursively = (node) => {
2025-06-05 08:21:39 +00:00
if (node.nodeType === Node.TEXT_NODE) {
2025-06-11 08:54:54 +00:00
currentTextBuffer += node.textContent;
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
2025-06-11 08:54:54 +00:00
switch (node.tagName) {
case 'BR':
currentTextBuffer += '\n';
2025-06-11 08:54:54 +00:00
break;
case 'IMG':
flushTextBufferIfNeeded();
const src = node.getAttribute('src');
const alt = node.getAttribute('alt');
const isEmojiPic = node.classList.contains('editor-emoji');
const isTextEmojiPlaceholder = node.classList.contains('emoji');
2025-06-11 08:54:54 +00:00
if (isTextEmojiPlaceholder && alt) {
currentTextBuffer += alt;
2025-06-11 08:54:54 +00:00
} else if (src) {
items.push({
2025-06-24 08:27:00 +00:00
type: 3,
content: src,
isEmoji: isEmojiPic,
2025-06-11 08:54:54 +00:00
width: node.getAttribute('data-original-width') || node.width || null,
height: node.getAttribute('data-original-height') || node.height || null,
});
}
break;
default:
if (node.classList.contains('mention')) {
const userId = node.getAttribute('data-user-id');
if (userId) {
mentionUids.add(Number(userId));
}
currentTextBuffer += node.textContent || '';
2025-06-11 08:54:54 +00:00
} else if (node.classList.contains('editor-file')) {
flushTextBufferIfNeeded();
const fileUrl = node.getAttribute('data-url');
const fileName = node.getAttribute('data-name');
const fileSize = node.getAttribute('data-size-raw') || node.getAttribute('data-size') || 0;
if (fileUrl && fileName) {
items.push({
2025-06-24 08:27:00 +00:00
type: 4,
content: fileUrl,
name: fileName,
size: parseInt(fileSize, 10),
2025-06-11 08:54:54 +00:00
});
}
} else if (node.childNodes && node.childNodes.length > 0) {
Array.from(node.childNodes).forEach(processNodeRecursively);
} else if (node.textContent) {
currentTextBuffer += node.textContent;
}
break;
}
};
Array.from(tempDiv.childNodes).forEach(processNodeRecursively);
flushTextBufferIfNeeded();
return {
2025-06-05 08:21:39 +00:00
items: items.length > 0 ? items : [{ type: 1, content: '' }],
2025-06-11 08:54:54 +00:00
mentionUids: Array.from(mentionUids),
quoteId: parsedQuoteId
};
};
2025-06-05 08:21:39 +00:00
const clearEditor = () => {
if (editorRef.value) {
2025-06-11 08:54:54 +00:00
editorRef.value.innerHTML = '';
2025-06-05 08:21:39 +00:00
}
2025-06-11 08:54:54 +00:00
editorContent.value = '';
editorHtml.value = '';
quoteData.value = null;
hideMentionList();
2025-06-11 08:54:54 +00:00
const existingQuoteElement = editorRef.value ? editorRef.value.querySelector('.editor-quote') : null;
if (existingQuoteElement) {
existingQuoteElement.remove();
}
handleInput();
2025-06-05 08:21:39 +00:00
emit('editor-event', {
event: 'clear_event',
2025-06-05 08:21:39 +00:00
data: ''
2025-06-11 08:54:54 +00:00
});
if (editorRef.value) {
nextTick(() => {
editorRef.value.focus();
if (editorRef.value && editorRef.value.innerHTML.toLowerCase() === '<br>') {
2025-06-11 08:54:54 +00:00
editorRef.value.innerHTML = '';
}
});
}
};
const insertImage = (fileOrSrc, isUploaded = false, uploadedUrl = '') => {
if (!editorRef.value) return;
const img = document.createElement('img');
img.className = 'editor-image';
img.alt = '图片';
img.style.maxWidth = '200px';
img.style.maxHeight = '200px';
2025-06-11 08:54:54 +00:00
img.style.borderRadius = '4px';
img.style.objectFit = 'contain';
img.style.margin = '5px';
const wrapper = document.createElement('span');
wrapper.className = 'editor-image-wrapper';
wrapper.style.position = 'relative';
wrapper.style.display = 'inline-block';
wrapper.appendChild(img);
2025-06-11 08:54:54 +00:00
const setupAndInsert = (imageUrl, naturalWidth, naturalHeight) => {
img.src = imageUrl;
if (naturalWidth) img.setAttribute('data-original-width', naturalWidth);
if (naturalHeight) img.setAttribute('data-original-height', naturalHeight);
if (isUploaded && uploadedUrl) {
img.setAttribute('data-uploaded-url', uploadedUrl);
img.setAttribute('data-status', 'uploaded');
} else {
img.setAttribute('data-status', 'local-preview');
}
const selection = window.getSelection();
let range;
if (selection && selection.rangeCount > 0) {
range = selection.getRangeAt(0);
if (!editorRef.value.contains(range.commonAncestorContainer)) {
editorRef.value.focus();
range = document.createRange();
range.selectNodeContents(editorRef.value);
range.collapse(false);
2025-06-11 08:54:54 +00:00
}
} else {
editorRef.value.focus();
range = document.createRange();
range.selectNodeContents(editorRef.value);
range.collapse(false);
2025-06-11 08:54:54 +00:00
}
range.deleteContents();
range.insertNode(wrapper);
const spaceNode = document.createTextNode('\u00A0');
2025-06-11 08:54:54 +00:00
range.insertNode(spaceNode);
range.setStartAfter(spaceNode);
range.collapse(false);
2025-06-11 08:54:54 +00:00
selection.removeAllRanges();
selection.addRange(range);
editorRef.value.focus();
handleInput();
2025-06-11 08:54:54 +00:00
};
if (typeof fileOrSrc === 'string') {
2025-06-11 08:54:54 +00:00
const tempImageForSize = new Image();
tempImageForSize.onload = () => {
setupAndInsert(fileOrSrc, tempImageForSize.naturalWidth, tempImageForSize.naturalHeight);
};
tempImageForSize.onerror = () => {
console.warn('Failed to load image from URL for size calculation:', fileOrSrc);
setupAndInsert(fileOrSrc);
2025-06-11 08:54:54 +00:00
};
tempImageForSize.src = fileOrSrc;
} else if (fileOrSrc instanceof File && fileOrSrc.type.startsWith('image/')) {
2025-06-11 08:54:54 +00:00
const reader = new FileReader();
reader.onload = (e) => {
const dataUrl = e.target.result;
const tempImageForSize = new Image();
tempImageForSize.onload = () => {
setupAndInsert(dataUrl, tempImageForSize.naturalWidth, tempImageForSize.naturalHeight);
};
tempImageForSize.onerror = () => {
console.warn('Failed to load image from FileReader for size calculation.');
setupAndInsert(dataUrl);
2025-06-11 08:54:54 +00:00
};
tempImageForSize.src = dataUrl;
};
reader.onerror = (error) => {
console.error('FileReader error:', error);
};
reader.readAsDataURL(fileOrSrc);
} else {
console.warn('insertImage: Invalid file object or URL provided.');
}
2025-06-24 08:27:00 +00:00
return img;
2025-06-11 08:54:54 +00:00
};
2025-06-05 08:21:39 +00:00
const formatFileSize = (size) => {
if (size < 1024) {
return size + ' B'
} else if (size < 1024 * 1024) {
return (size / 1024).toFixed(2) + ' KB'
} else if (size < 1024 * 1024 * 1024) {
return (size / (1024 * 1024)).toFixed(2) + ' MB'
} else {
return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
}
}
2025-06-11 08:54:54 +00:00
const onUploadSendImg = async (event) => {
if (!event.target || !event.target.files) return;
const files = event.target.files;
for (const file of files) {
if (!file.type.startsWith('image/')) {
console.warn('Invalid file type for image upload:', file.type);
continue;
}
const formData = new FormData();
formData.append('file', file);
2025-06-24 08:27:00 +00:00
formData.append('source', 'fonchain-chat');
2025-06-11 08:54:54 +00:00
try {
const res = await uploadImg(formData);
if (res && res.status === 0 && res.data && res.data.ori_url) {
const previewImages = editorRef.value.querySelectorAll('img[data-status="local-preview"][src^="data:image"]:not([data-uploaded-url])');
if (previewImages.length > 0) {
const lastPreviewImage = previewImages[previewImages.length - 1];
if (lastPreviewImage && lastPreviewImage.src.startsWith('data:image')) {
lastPreviewImage.src = res.data.ori_url;
lastPreviewImage.setAttribute('data-uploaded-url', res.data.ori_url);
lastPreviewImage.setAttribute('data-status', 'uploaded');
if (res.data.width) lastPreviewImage.setAttribute('data-original-width', res.data.width);
if (res.data.height) lastPreviewImage.setAttribute('data-original-height', res.data.height);
2025-06-24 08:27:00 +00:00
handleInput();
2025-06-11 08:54:54 +00:00
}
}
2025-06-11 08:54:54 +00:00
emit('editor-event', emitCall('image_event', {
url: res.data.ori_url,
width: res.data.width || 0,
height: res.data.height || 0,
size: 10000
2025-06-11 08:54:54 +00:00
}));
} else {
console.error('Image upload failed or received invalid response:', res);
const previewImages = editorRef.value.querySelectorAll('img[data-status="local-preview"][src^="data:image"]:not([data-uploaded-url])');
if (previewImages.length > 0) {
const lastPreviewImage = previewImages[previewImages.length -1];
if(lastPreviewImage) {
lastPreviewImage.style.border = '2px dashed red';
lastPreviewImage.title = 'Upload failed';
}
}
}
} catch (error) {
console.error('Error during image upload process:', error);
const previewImages = editorRef.value.querySelectorAll('img[data-status="local-preview"][src^="data:image"]:not([data-uploaded-url])');
if (previewImages.length > 0) {
const lastPreviewImage = previewImages[previewImages.length -1];
if(lastPreviewImage) {
lastPreviewImage.style.border = '2px dashed red';
lastPreviewImage.title = 'Upload error';
}
}
}
}
if (event.target) event.target.value = '';
2025-06-11 08:54:54 +00:00
};
async function onUploadFile(e) {
if (!e.target || !e.target.files || e.target.files.length === 0) return;
const file = e.target.files[0];
e.target.value = null;
const fileType = file.type;
let eventName = '';
if (fileType.startsWith('image/')) {
eventName = 'image_event';
emit('editor-event', emitCall(eventName, file));
} else if (fileType.startsWith('video/')) {
eventName = 'video_event';
emit('editor-event', emitCall(eventName, file));
2025-06-05 08:21:39 +00:00
} else {
2025-06-11 08:54:54 +00:00
eventName = 'file_event';
emit('editor-event', emitCall(eventName, file));
2025-06-05 08:21:39 +00:00
}
}
const onEmoticonEvent = (emoji) => {
emoticonRef.value?.setShow(false)
switch (emoji.type) {
case 'text':
case 'emoji':
2025-06-05 08:21:39 +00:00
insertTextEmoji(emoji.value)
break
case 'image':
insertImageEmoji(emoji.img, emoji.value)
break
case 1:
emoji.img ? insertImageEmoji(emoji.img, emoji.value) : insertTextEmoji(emoji.value)
break
default:
emit('editor-event', {
event: 'emoticon_event',
data: emoji.value || emoji.id
})
break
2025-06-05 08:21:39 +00:00
}
}
const insertTextEmoji = (emojiText) => {
2025-06-11 08:54:54 +00:00
if (!editorRef.value || typeof emojiText !== 'string') return;
const editor = editorRef.value;
2025-06-24 08:27:00 +00:00
editor.focus();
2025-06-11 08:54:54 +00:00
const selection = window.getSelection();
let range;
if (selection && selection.rangeCount > 0) {
range = selection.getRangeAt(0);
if (!editor.contains(range.commonAncestorContainer)) {
range = document.createRange();
range.selectNodeContents(editor);
2025-06-24 08:27:00 +00:00
range.collapse(false);
2025-06-11 08:54:54 +00:00
}
} else {
range = document.createRange();
range.selectNodeContents(editor);
2025-06-24 08:27:00 +00:00
range.collapse(false);
2025-06-11 08:54:54 +00:00
}
range.deleteContents();
2025-06-11 08:54:54 +00:00
const textNode = document.createTextNode(emojiText);
range.insertNode(textNode);
range.setStartAfter(textNode);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
handleInput();
2025-06-11 08:54:54 +00:00
};
2025-06-05 08:21:39 +00:00
const insertImageEmoji = (imgSrc, altText) => {
2025-06-11 08:54:54 +00:00
if (!editorRef.value || !imgSrc) return;
const editor = editorRef.value;
2025-06-24 08:27:00 +00:00
editor.focus();
2025-06-11 08:54:54 +00:00
const selection = window.getSelection();
let range;
if (selection && selection.rangeCount > 0) {
range = selection.getRangeAt(0);
if (!editor.contains(range.commonAncestorContainer)) {
range = document.createRange();
range.selectNodeContents(editor);
2025-06-24 08:27:00 +00:00
range.collapse(false);
2025-06-11 08:54:54 +00:00
}
} else {
range = document.createRange();
range.selectNodeContents(editor);
2025-06-24 08:27:00 +00:00
range.collapse(false);
2025-06-11 08:54:54 +00:00
}
range.deleteContents();
2025-06-11 08:54:54 +00:00
const img = document.createElement('img');
img.src = imgSrc;
2025-06-24 08:27:00 +00:00
img.alt = altText || 'emoji';
img.className = 'editor-emoji';
img.setAttribute('data-role', 'emoji');
2025-06-11 08:54:54 +00:00
range.insertNode(img);
const spaceNode = document.createTextNode('\u00A0');
2025-06-11 08:54:54 +00:00
range.setStartAfter(img);
range.collapse(true);
range.insertNode(spaceNode);
range.setStartAfter(spaceNode);
range.collapse(true);
if (selection) {
selection.removeAllRanges();
selection.addRange(range);
}
handleInput();
2025-06-11 08:54:54 +00:00
};
const onSubscribeMention = async (data) => {
2025-06-11 08:54:54 +00:00
if (!editorRef.value || !data) return;
const editorNode = editorRef.value;
editorNode.focus();
await nextTick();
let selection = window.getSelection();
2025-06-11 08:54:54 +00:00
let range;
if (selection && selection.rangeCount > 0) {
range = selection.getRangeAt(0);
if (!editorNode.contains(range.commonAncestorContainer)) {
range = document.createRange();
range.selectNodeContents(editorNode);
2025-06-24 08:27:00 +00:00
range.collapse(false);
}
2025-06-11 08:54:54 +00:00
} else {
range = document.createRange();
range.selectNodeContents(editorNode);
2025-06-24 08:27:00 +00:00
range.collapse(false);
2025-06-11 08:54:54 +00:00
}
if (selection) {
selection.removeAllRanges();
selection.addRange(range);
2025-06-24 08:27:00 +00:00
insertMention(data, range);
2025-06-11 08:54:54 +00:00
} else {
const fallbackRange = document.createRange();
fallbackRange.selectNodeContents(editorNode);
2025-06-24 08:27:00 +00:00
fallbackRange.collapse(false);
const newSelection = window.getSelection();
2025-06-11 08:54:54 +00:00
if (newSelection){
newSelection.removeAllRanges();
newSelection.addRange(fallbackRange);
2025-06-24 08:27:00 +00:00
insertMention(data, fallbackRange);
} else {
2025-06-11 08:54:54 +00:00
console.error("Could not get window selection to insert mention.");
}
}
};
const handleDeleteQuote = function(e) {
if (e.key !== 'Backspace' && e.key !== 'Delete') return;
const selection = window.getSelection();
if (selection.rangeCount === 0) return;
const range = selection.getRangeAt(0);
const editor = editorRef.value;
if (!editor) return;
const quoteElement = editor.querySelector('.editor-quote');
if (!quoteElement) {
editor.removeEventListener('keydown', handleDeleteQuote);
return;
}
const quoteIndex = Array.from(editor.childNodes).indexOf(quoteElement);
const isBeforeQuote = e.key === 'Backspace' &&
range.collapsed &&
range.startContainer === editor &&
quoteIndex === range.startOffset;
const isAfterQuote = e.key === 'Delete' &&
range.collapsed &&
range.startContainer === editor &&
quoteIndex === range.startOffset - 1;
if (isBeforeQuote || isAfterQuote) {
e.preventDefault();
quoteElement.remove();
quoteData.value = null;
handleInput({ target: editor });
}
};
2025-06-05 08:21:39 +00:00
const onSubscribeQuote = (data) => {
2025-06-11 08:54:54 +00:00
if (!editorRef.value || !data) return;
quoteData.value = data;
const editor = editorRef.value;
editor.querySelectorAll('.editor-quote').forEach(quote => quote.remove());
const selection = window.getSelection();
let savedRange = null;
if (selection && selection.rangeCount > 0) {
const currentRange = selection.getRangeAt(0);
if (editor.contains(currentRange.commonAncestorContainer)) {
savedRange = currentRange.cloneRange();
}
}
const quoteElement = document.createElement('div');
quoteElement.className = 'editor-quote';
2025-06-24 08:27:00 +00:00
quoteElement.contentEditable = 'false';
2025-06-11 08:54:54 +00:00
const wrapper = document.createElement('div');
wrapper.className = 'quote-content-wrapper';
const titleDiv = document.createElement('div');
titleDiv.className = 'quote-title';
2025-06-24 08:27:00 +00:00
titleDiv.textContent = data.title || ' ';
2025-06-11 08:54:54 +00:00
wrapper.appendChild(titleDiv);
if (data.image) {
const imageDiv = document.createElement('div');
imageDiv.className = 'quote-image';
const img = document.createElement('img');
img.src = data.image;
img.alt = '引用图片';
imageDiv.appendChild(img);
wrapper.appendChild(imageDiv);
}
if (data.describe) {
const contentDiv = document.createElement('div');
contentDiv.className = 'quote-content';
contentDiv.textContent = data.describe;
wrapper.appendChild(contentDiv);
}
quoteElement.appendChild(wrapper);
const closeButton = document.createElement('div');
closeButton.className = 'quote-close';
closeButton.textContent = '×';
quoteElement.appendChild(closeButton);
2025-06-05 08:21:39 +00:00
if (editor.firstChild) {
2025-06-11 08:54:54 +00:00
editor.insertBefore(quoteElement, editor.firstChild);
2025-06-05 08:21:39 +00:00
} else {
2025-06-11 08:54:54 +00:00
editor.appendChild(quoteElement);
2025-06-05 08:21:39 +00:00
}
2025-06-11 08:54:54 +00:00
let nodeToPlaceCursorAfter = quoteElement;
2025-06-24 08:27:00 +00:00
const zeroWidthSpace = document.createTextNode('\u200B');
2025-06-11 08:54:54 +00:00
if (editor.lastChild === quoteElement || !quoteElement.nextSibling) {
editor.appendChild(zeroWidthSpace);
nodeToPlaceCursorAfter = zeroWidthSpace;
2025-06-05 08:21:39 +00:00
} else {
2025-06-11 08:54:54 +00:00
editor.insertBefore(zeroWidthSpace, quoteElement.nextSibling);
nodeToPlaceCursorAfter = zeroWidthSpace;
}
const handleQuoteClick = (e) => {
2025-06-24 08:27:00 +00:00
e.stopPropagation();
2025-06-11 08:54:54 +00:00
if (e.target === closeButton || closeButton.contains(e.target)) {
quoteElement.remove();
if (nodeToPlaceCursorAfter.parentNode === editor && nodeToPlaceCursorAfter.nodeValue === '\u200B') {
nodeToPlaceCursorAfter.remove();
}
quoteData.value = null;
editor.removeEventListener('keydown', handleDeleteQuote);
handleInput();
2025-06-11 08:54:54 +00:00
editor.focus();
2025-06-05 08:21:39 +00:00
} else {
2025-06-11 08:54:54 +00:00
const newRange = document.createRange();
newRange.setStartAfter(nodeToPlaceCursorAfter.parentNode === editor ? nodeToPlaceCursorAfter : quoteElement);
newRange.collapse(true);
if (selection) {
selection.removeAllRanges();
selection.addRange(newRange);
}
editor.focus();
2025-06-05 08:21:39 +00:00
}
2025-06-11 08:54:54 +00:00
};
quoteElement.addEventListener('click', handleQuoteClick);
editor.addEventListener('keydown', handleDeleteQuote);
setTimeout(() => {
2025-06-05 08:21:39 +00:00
editor.focus();
2025-06-11 08:54:54 +00:00
const newSelection = window.getSelection();
if (!newSelection) return;
let cursorPlaced = false;
if (savedRange) {
2025-06-11 08:54:54 +00:00
try {
if (editor.contains(savedRange.commonAncestorContainer) && savedRange.startContainer) {
2025-06-11 08:54:54 +00:00
newSelection.removeAllRanges();
newSelection.addRange(savedRange);
cursorPlaced = true;
}
} catch (err) {
}
2025-06-05 08:21:39 +00:00
}
2025-06-11 08:54:54 +00:00
if (!cursorPlaced) {
const newRange = document.createRange();
if (nodeToPlaceCursorAfter && nodeToPlaceCursorAfter.parentNode === editor) {
2025-06-11 08:54:54 +00:00
newRange.setStartAfter(nodeToPlaceCursorAfter);
} else if (quoteElement.parentNode === editor && quoteElement.nextSibling) {
newRange.setStartAfter(quoteElement.nextSibling);
2025-06-11 08:54:54 +00:00
} else if (quoteElement.parentNode === editor) {
newRange.setStartAfter(quoteElement);
2025-06-11 08:54:54 +00:00
} else {
newRange.selectNodeContents(editor);
2025-06-11 08:54:54 +00:00
newRange.collapse(false);
}
newRange.collapse(true);
newSelection.removeAllRanges();
newSelection.addRange(newRange);
}
editor.scrollTop = editor.scrollHeight;
handleInput();
2025-06-24 08:27:00 +00:00
}, 0);
};
2025-06-05 08:21:39 +00:00
const onSubscribeEdit = (data) => {
editingMessage.value = data
clearEditor()
if (data.content) {
editorRef.value.innerHTML = data.content
editorContent.value = data.content
editorHtml.value = data.content
}
}
const onSubscribeClear = () => {
clearEditor()
}
const saveDraft = () => {
if (!indexName.value || !editorRef.value) return
const fragment = document.createDocumentFragment()
const tempDiv = document.createElement('div')
tempDiv.innerHTML = editorRef.value.innerHTML
fragment.appendChild(tempDiv)
const quoteElements = tempDiv.querySelectorAll('.editor-quote')
quoteElements.forEach(quote => quote.remove())
const contentToSave = tempDiv.textContent || ''
const htmlToSave = tempDiv.innerHTML || ''
const currentEditor= parseEditorContent().items
const hasContent = contentToSave.trim().length > 0 ||
htmlToSave.includes('<img') ||
htmlToSave.includes('editor-file')
if (currentEditor.length>0) {
2025-06-05 08:21:39 +00:00
editorDraftStore.items[indexName.value] = JSON.stringify({
content: currentEditor.reduce((result, x) => {
2025-06-24 08:27:00 +00:00
if (x.type === 3) return result + '[图片]'
if (x.type === 1) return result + x.content
return result
}, ''),
2025-06-24 08:27:00 +00:00
html: htmlToSave
2025-06-05 08:21:39 +00:00
})
} else {
delete editorDraftStore.items[indexName.value]
}
}
const loadDraft = () => {
if (!indexName.value) return
nextTick(() => {
2025-06-05 08:21:39 +00:00
const currentQuoteData = quoteData.value
quoteData.value = null
if (!editorRef.value) return
editorRef.value.innerHTML = ''
editorContent.value = ''
editorHtml.value = ''
2025-06-05 08:21:39 +00:00
const draft = editorDraftStore.items[indexName.value]
if (draft) {
try {
const draftData = JSON.parse(draft)
editorRef.value.innerHTML = draftData.html || ''
editorContent.value = draftData.content || ''
editorHtml.value = draftData.html || ''
2025-06-05 08:21:39 +00:00
} catch (error) {
console.warn('加载草稿失败,使用空内容', error)
2025-06-05 08:21:39 +00:00
}
}
if (currentQuoteData) {
onSubscribeQuote(currentQuoteData)
}
})
2025-06-05 08:21:39 +00:00
}
watch(indexName, loadDraft, { immediate: true })
const handleDocumentClick = (event) => {
if (!editorRef.value?.contains(event.target)) {
hideMentionList()
}
}
2025-06-05 08:21:39 +00:00
onMounted(() => {
const subscriptions = [
2025-06-24 08:27:00 +00:00
[EditorConst.Mention, onSubscribeMention],
[EditorConst.Quote, onSubscribeQuote],
[EditorConst.Edit, onSubscribeEdit],
[EditorConst.Clear, onSubscribeClear]
]
subscriptions.forEach(([event, handler]) => {
bus.subscribe(event, handler)
2025-06-05 08:21:39 +00:00
})
editorRef.value?.addEventListener('click', handleEditorClick)
document.addEventListener('click', handleDocumentClick)
2025-06-05 08:21:39 +00:00
loadDraft()
})
onBeforeUnmount(() => {
const subscriptions = [
[EditorConst.Mention, onSubscribeMention],
[EditorConst.Quote, onSubscribeQuote],
[EditorConst.Edit, onSubscribeEdit],
[EditorConst.Clear, onSubscribeClear]
]
subscriptions.forEach(([event, handler]) => {
bus.unsubscribe(event, handler)
})
editorRef.value?.removeEventListener('click', handleEditorClick)
document.removeEventListener('click', handleDocumentClick)
2025-06-05 08:21:39 +00:00
const editor = editorRef.value
if (editor && handleDeleteQuote) {
editor.removeEventListener('keydown', handleDeleteQuote)
}
})
const onEmoticonSelect = (emoji) => {
onEmoticonEvent(emoji)
isShowEmoticon.value = false
}
const onCodeSubmit = (data) => {
emit('editor-event', {
event: 'code_event',
data,
callBack: () => {}
})
isShowCode.value = false
}
const onVoteSubmit = (data) => {
emit('editor-event', {
event: 'vote_event',
data,
callBack: () => {}
})
isShowVote.value = false
}
const handleEditorClick = (event) => {
const closeButton = event.target.closest('.quote-close');
if (closeButton) {
const quoteElement = event.target.closest('.editor-quote');
if (quoteElement) {
quoteElement.remove();
quoteData.value = null;
handleInput({ target: editorRef.value });
event.preventDefault();
event.stopPropagation();
}
}
const isMentionListClick = event.target.closest('.mention-list');
if (showMention.value && !isMentionListClick) {
hideMentionList();
}
};
2025-06-05 08:21:39 +00:00
</script>
<template>
<section class="el-container editor">
<section class="el-container is-vertical">
<header class="el-header toolbar bdr-t">
<div class="tools pr-30px">
2025-06-05 08:21:39 +00:00
<n-popover
placement="top-start"
trigger="click"
raw
:show-arrow="false"
:width="300"
ref="emoticonRef"
style="width: 500px; height: 250px; border-radius: 10px; overflow: hidden"
>
<template #trigger>
<div class="item pointer">
<n-icon size="18" class="icon" :component="SmilingFace" />
<p class="tip-title">表情符号</p>
</div>
</template>
<MeEditorEmoticon @on-select="onEmoticonEvent" />
</n-popover>
<div
class="item pointer"
v-for="nav in navs"
:key="nav.title"
v-show="nav.show"
@click="nav.click"
>
<n-icon size="18" class="icon" :component="nav.icon" />
<p class="tip-title">{{ nav.title }}</p>
</div>
<n-button class="w-80px h-30px ml-auto" type="primary" @click="sendMessage">
<template #icon>
<n-icon>
<IosSend />
</n-icon>
</template>
发送
</n-button>
2025-06-05 08:21:39 +00:00
</div>
</header>
<main class="el-main height100">
<div
ref="editorRef"
class="custom-editor"
contenteditable="true"
:placeholder="placeholder"
@input="handleInput"
@keydown="handleKeydown"
@paste="handlePaste"
@focus="handleFocus"
@blur="handleBlur"
></div>
<div
v-if="showMention && dialogueStore.talk.talk_type === 2"
class="mention-list py-5px"
2025-06-05 08:21:39 +00:00
:style="{ top: mentionPosition.top + 'px', left: mentionPosition.left + 'px' }"
>
<ul class="max-h-140px w-163px overflow-auto hide-scrollbar">
<li
2025-06-05 08:21:39 +00:00
v-for="(member, index) in mentionList"
:key="member.user_id || member.id"
class="cursor-pointer px-14px h-42px"
:class="{ 'bg-#EEE9F9': index === selectedMentionIndex }"
@mousedown.prevent="handleMentionSelectByMouse(member)"
@mouseover="selectedMentionIndex = index"
2025-06-05 08:21:39 +00:00
>
<div class="flex items-center border-b-1px border-b-solid border-b-#F8F8F8 h-full">
<img class="w-26px h-26px rounded-50% mr-11px" :src="member.avatar" alt="">
<span>{{ member.nickname }}</span>
</div>
</li>
2025-06-05 08:21:39 +00:00
</ul>
</div>
</main>
</section>
</section>
<form enctype="multipart/form-data" style="display: none">
<input type="file" ref="fileImageRef" accept="image/*" @change="onUploadSendImg" />
2025-06-05 08:21:39 +00:00
<input type="file" ref="uploadFileRef" @change="onUploadFile" />
</form>
</template>
<style lang="less" scoped>
.editor {
--tip-bg-color: rgb(241 241 241 / 90%);
height: 100%;
.toolbar {
height: 38px;
display: flex;
.tools {
height: 40px;
2025-06-05 08:21:39 +00:00
flex: auto;
display: flex;
align-items: center;
2025-06-05 08:21:39 +00:00
.item {
display: flex;
align-items: center;
justify-content: center;
width: 35px;
margin: 0 2px;
position: relative;
user-select: none;
2025-06-05 08:21:39 +00:00
.tip-title {
display: none;
position: absolute;
top: 40px;
left: 0px;
line-height: 26px;
background-color: var(--tip-bg-color);
color: var(--im-text-color);
min-width: 20px;
font-size: 12px;
padding: 0 5px;
border-radius: 2px;
white-space: pre;
2025-06-05 08:21:39 +00:00
user-select: none;
z-index: 999999999999;
2025-06-05 08:21:39 +00:00
}
&:hover {
.tip-title {
display: block;
}
}
}
}
}
:deep(.editor-file) {
display: inline-block;
padding: 5px 10px;
margin: 5px 0;
background-color: #f5f5f5;
border: 1px solid #e0e0e0;
border-radius: 4px;
color: #462AA0;
2025-06-05 08:21:39 +00:00
text-decoration: none;
position: relative;
padding-right: 60px;
2025-06-05 08:21:39 +00:00
max-width: 100%;
box-sizing: border-box;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
2025-06-05 08:21:39 +00:00
&::after {
content: attr(data-size);
position: absolute;
right: 10px;
color: #757575;
font-size: 12px;
}
&:hover {
background-color: #e3f2fd;
}
}
:deep(.editor-emoji) {
display: inline-block;
width: 24px;
height: 24px;
vertical-align: middle;
2025-06-05 08:21:39 +00:00
margin: 0 2px;
}
:deep(.editor-quote) {
margin-bottom: 8px;
padding: 8px 12px;
background-color: var(--im-message-left-bg-color, #f5f5f5);
border-left: 3px solid var(--im-primary-color, #409eff);
border-radius: 4px;
font-size: 13px;
position: relative;
display: flex;
justify-content: space-between;
align-items: flex-start;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
cursor: pointer;
user-select: none;
transition: background-color 0.2s ease;
2025-06-05 08:21:39 +00:00
&:hover {
background-color: var(--im-message-left-bg-hover-color, #eaeaea);
}
.quote-content-wrapper {
flex: 1;
overflow: hidden;
}
.quote-title {
color: var(--im-primary-color, #409eff);
margin-bottom: 4px;
font-weight: 500;
}
.quote-content {
color: var(--im-text-color, #333);
word-break: break-all;
white-space: normal;
2025-06-05 08:21:39 +00:00
overflow: hidden;
text-overflow: ellipsis;
2025-06-05 08:21:39 +00:00
display: -webkit-box;
-webkit-line-clamp: 2;
2025-06-05 08:21:39 +00:00
-webkit-box-orient: vertical;
}
.quote-image img {
max-width: 100px;
max-height: 60px;
border-radius: 3px;
pointer-events: none;
2025-06-05 08:21:39 +00:00
}
.quote-close {
width: 18px;
height: 18px;
line-height: 16px;
text-align: center;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.1);
color: #666;
cursor: pointer;
font-size: 16px;
margin-left: 8px;
user-select: none;
&:hover {
background-color: rgba(0, 0, 0, 0.2);
color: #333;
}
}
}
.custom-editor {
width: 100%;
height: 100%;
padding: 8px;
border: none;
outline: none;
resize: none;
font-size: 14px;
line-height: 1.5;
color: #333;
background: transparent;
overflow-y: auto;
&:empty:before {
content: attr(placeholder);
color: #999;
pointer-events: none;
}
2025-06-05 08:21:39 +00:00
&::-webkit-scrollbar {
width: 3px;
height: 3px;
background-color: unset;
}
&::-webkit-scrollbar-thumb {
border-radius: 3px;
background-color: transparent;
}
&:hover {
&::-webkit-scrollbar-thumb {
background-color: var(--im-scrollbar-thumb);
}
}
}
.custom-editor:empty::before {
content: attr(placeholder);
color: #999;
pointer-events: none;
2025-06-05 08:21:39 +00:00
font-family: PingFang SC, Microsoft YaHei, 'Alibaba PuHuiTi 2.0 45' !important;
}
.custom-editor:focus {
outline: none;
}
.mention:hover {
background-color: #bae7ff;
}
.editor-emoji {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0 2px;
}
.mention-list {
position: absolute;
background-color: white;
border: 1px solid #eee;
border-radius: 4px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
z-index: 1000;
}
.quote-card {
background: #f5f5f5;
border-left: 3px solid #1890ff;
padding: 8px 12px;
margin: 8px 0;
border-radius: 4px;
position: relative;
}
.quote-content {
font-size: 12px;
}
.quote-title {
font-weight: bold;
color: #1890ff;
margin-bottom: 4px;
}
.quote-text {
color: #666;
line-height: 1.4;
}
.quote-close {
position: absolute;
top: 4px;
right: 4px;
background: none;
border: none;
cursor: pointer;
color: #999;
font-size: 12px;
}
.edit-tip {
background: #fff7e6;
border: 1px solid #ffd591;
padding: 6px 12px;
margin-bottom: 8px;
border-radius: 4px;
font-size: 12px;
color: #d46b08;
display: flex;
align-items: center;
gap: 8px;
}
.edit-tip button {
background: none;
border: none;
cursor: pointer;
color: #d46b08;
margin-left: auto;
}
}
html[theme-mode='dark'] {
.editor {
--tip-bg-color: #48484d;
}
}
:deep(.editor-image-wrapper.image-upload-loading::before) {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 24px;
height: 24px;
margin-top: -12px;
margin-left: -12px;
border: 2px solid rgba(0, 0, 0, 0.1);
border-top-color: #333;
border-radius: 50%;
animation: spin 0.6s linear infinite;
z-index: 1;
}
:deep(.editor-image-wrapper.image-upload-loading img) {
opacity: 0.5;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.hide-scrollbar {
&::-webkit-scrollbar {
width: 0;
display: none;
}
scrollbar-width: none;
-ms-overflow-style: none;
}
2025-06-05 08:21:39 +00:00
</style>