Browse Source

翻译功能完善

master
La123123 4 weeks ago
parent
commit
a3f2ffefb2
  1. 35
      im-web/src/components/chat/ChatBox.vue
  2. 91
      im-web/src/components/chat/ChatInput.vue

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

@ -122,7 +122,7 @@
</el-select>
<el-button
type="primary"
@click="translateMessage(countryCode)"
@click="translateInput(countryCode)"
>翻译</el-button
>
<el-button
@ -1323,6 +1323,39 @@ export default {
});
return res;
},
//
async translateInput(country) {
try {
//
const chatInput = this.$refs.chatInputEditor;
if (!chatInput.isPureText()) {
this.$message.error("只能翻译纯文本内容");
return;
}
//
const text = chatInput.getTextContent();
if (!text || text.trim() === "") {
this.$message.warning("请输入需要翻译的文本内容");
return;
}
// API
const res = await this.translateTextToOther(text, country);
//
if (res) {
//
chatInput.setTextContent(res);
this.$message.success("翻译成功");
} else {
this.$message.error(res);
}
} catch (error) {
console.error("翻译出错:", error);
this.$message.error("翻译出错,请稍后重试");
}
},
},
computed: {
mine() {

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

@ -450,6 +450,97 @@ export default {
},
focus() {
this.$refs.content.focus();
},
//
isPureText() {
let nodes = this.$refs.content.childNodes;
let hasNonTextContent = false;
let each = (nodes) => {
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i];
if (!node) {
continue;
}
//
if (node.nodeType === 3) {
continue;
}
let nodeName = node.nodeName.toLowerCase();
// script
if (nodeName === 'script') {
continue;
}
// emoji
if (nodeName === 'img') {
hasNonTextContent = true;
return;
}
//
if (nodeName === 'div' && node.dataset.fileId) {
hasNonTextContent = true;
return;
}
// @
if (nodeName === 'span' && node.dataset.id) {
hasNonTextContent = true;
return;
}
//
if (node.childNodes && node.childNodes.length > 0) {
each(node.childNodes);
if (hasNonTextContent) {
return;
}
}
}
};
each(nodes);
return !hasNonTextContent;
},
//
getTextContent() {
let nodes = this.$refs.content.childNodes;
let textContent = '';
let each = (nodes) => {
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i];
if (!node) {
continue;
}
//
if (node.nodeType === 3) {
textContent += node.textContent;
continue;
}
let nodeName = node.nodeName.toLowerCase();
// script
if (nodeName === 'script') {
continue;
}
// div
if (nodeName === 'div' && !node.dataset.fileId) {
textContent += '\n';
each(node.childNodes);
continue;
}
//
if (node.childNodes && node.childNodes.length > 0) {
each(node.childNodes);
}
}
};
each(nodes);
return textContent.trim();
},
//
setTextContent(text) {
//
this.$refs.content.innerHTML = "";
// content
let textNode = document.createTextNode(text);
this.$refs.content.appendChild(textNode);
//
this.selectElement(textNode, text.length);
}
}

Loading…
Cancel
Save