447 lines
12 KiB
Vue
447 lines
12 KiB
Vue
<template>
|
||
<div class="editor-shell">
|
||
<EditorToolbar
|
||
:default-config="toolbarConfig"
|
||
:editor="editorRef"
|
||
class="editor-toolbar"
|
||
mode="default"
|
||
/>
|
||
<div :style="styles" class="editor-body">
|
||
<WangEditor
|
||
v-model="content"
|
||
:default-config="editorConfig"
|
||
class="editor-content"
|
||
mode="default"
|
||
@onChange="handleChange"
|
||
@onCreated="handleCreated"
|
||
/>
|
||
</div>
|
||
<div class="editor-footer">
|
||
<div v-if="simpleToolbar" class="editor-tip">
|
||
<p>请输入标准回复话术,可使用「有序步骤」插入分步指引,例如:</p>
|
||
<div class="demo-box">
|
||
<ol>
|
||
<li>确认设备已通电并处于配网模式(指示灯橙色快闪)</li>
|
||
<li>打开APP「我的设备」→ 添加设备,选择对应型号</li>
|
||
<li>输入2.4G Wi-Fi密码并等待约30秒完成连接</li>
|
||
</ol>
|
||
</div>
|
||
<p>以上为示例格式</p>
|
||
<p>支持插入图片与链接;回复中可引用设备型号,帮助用户快速对号入座</p>
|
||
</div>
|
||
<div class="counter-bar">
|
||
<span
|
||
:class="{ warn: textCount >= props.maxTextLength, danger: textCount > props.maxTextLength }"
|
||
>
|
||
纯文本 {{ textCount }}/{{ props.maxTextLength }}
|
||
</span>
|
||
<span class="divider">|</span>
|
||
<span
|
||
:class="{ warn: imageCount >= props.maxImageCount, danger: imageCount > props.maxImageCount }"
|
||
>
|
||
图片 {{ imageCount }}/{{ props.maxImageCount }}
|
||
</span>
|
||
<span class="divider">|</span>
|
||
<span
|
||
:class="{ warn: linkCount >= props.maxLinkCount, danger: linkCount > props.maxLinkCount }"
|
||
>
|
||
链接 {{ linkCount }}/{{ props.maxLinkCount }}
|
||
</span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</template>
|
||
|
||
<script lang="ts" setup>
|
||
import '@wangeditor-next/editor/dist/css/style.css';
|
||
import type {IDomEditor, IEditorConfig, IToolbarConfig} from '@wangeditor-next/editor';
|
||
import {Editor as WangEditor, Toolbar as EditorToolbar} from '@wangeditor-next/editor-for-vue';
|
||
import modal from '@/plugins/modal';
|
||
import {propTypes} from '@/utils/propTypes';
|
||
import {globalHeaders} from '@/utils/request';
|
||
import {html2Text} from '@/utils';
|
||
import {shallowRef, ref, computed, watch, onBeforeUnmount} from 'vue';
|
||
|
||
const props = defineProps({
|
||
modelValue: propTypes.string,
|
||
height: propTypes.number.def(400),
|
||
minHeight: propTypes.number.def(400),
|
||
readOnly: propTypes.bool.def(false),
|
||
fileSize: propTypes.number.def(5),
|
||
videoSize: propTypes.number.def(100),
|
||
type: propTypes.string.def('url'),
|
||
simpleToolbar: propTypes.bool.def(false),
|
||
maxTextLength: propTypes.number.def(1000),
|
||
maxImageCount: propTypes.number.def(3),
|
||
maxLinkCount: propTypes.number.def(5)
|
||
});
|
||
|
||
const emit = defineEmits(['update:modelValue', 'countChange']);
|
||
|
||
const editorRef = shallowRef<IDomEditor>();
|
||
const content = ref('');
|
||
const textCount = ref(0);
|
||
const imageCount = ref(0);
|
||
const linkCount = ref(0);
|
||
const lastValidHtml = ref('');
|
||
|
||
const IMG_REGEX = /<img\b[^>]*>/gi;
|
||
const A_TAG_REGEX = /<a\b[^>]*>.*?<\/a>/gi;
|
||
|
||
const baseUrl = import.meta.env.VITE_APP_BASE_API;
|
||
const uploadOssUrl = baseUrl + '/resource/oss/upload';
|
||
|
||
const styles = computed(() => {
|
||
const style: Record<string, string> = {};
|
||
if (props.minHeight) {
|
||
style.minHeight = `${props.minHeight}px`;
|
||
}
|
||
if (props.height) {
|
||
style.height = `${props.height}px`;
|
||
}
|
||
return style;
|
||
});
|
||
|
||
const toolbarConfig = computed<Partial<IToolbarConfig>>(() => {
|
||
if (props.simpleToolbar) {
|
||
return {
|
||
toolbarKeys: [
|
||
'bold',
|
||
'numberedList',
|
||
'uploadImage',
|
||
'insertLink',
|
||
'clearStyle',
|
||
],
|
||
excludeKeys: []
|
||
};
|
||
} else {
|
||
const excludeKeys: string[] = ['fullScreen'];
|
||
if (!props.type) {
|
||
excludeKeys.push('uploadImage');
|
||
excludeKeys.push('uploadVideo');
|
||
}
|
||
return {excludeKeys};
|
||
}
|
||
});
|
||
|
||
/* ==================== 内容度量 ==================== */
|
||
|
||
function measureHtml(html: string) {
|
||
const textLen = html2Text(html).length;
|
||
const imgMatch = html.match(IMG_REGEX);
|
||
const linkMatch = html.match(A_TAG_REGEX);
|
||
return {
|
||
textLen,
|
||
imgNum: imgMatch ? imgMatch.length : 0,
|
||
linkNum: linkMatch ? linkMatch.length : 0
|
||
};
|
||
}
|
||
|
||
/* ==================== OSS 上传 ==================== */
|
||
|
||
const uploadToOss = async (file: File): Promise<{ url: string; fileName: string }> => {
|
||
const formData = new FormData();
|
||
formData.append('file', file);
|
||
|
||
const res = await fetch(uploadOssUrl, {
|
||
method: 'POST',
|
||
headers: globalHeaders(),
|
||
body: formData
|
||
});
|
||
const data = await res.json();
|
||
|
||
if (data.code === 200) {
|
||
return data.data;
|
||
}
|
||
throw new Error(data.msg || '上传失败');
|
||
};
|
||
|
||
/* ==================== 文件校验 ==================== */
|
||
|
||
const validateImageFile = (file: File) => {
|
||
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/svg', 'image/svg+xml'];
|
||
if (!allowedTypes.includes(file.type)) {
|
||
modal.msgError('图片格式错误!');
|
||
return false;
|
||
}
|
||
|
||
if (props.fileSize) {
|
||
const isLt = file.size / 1024 / 1024 < props.fileSize;
|
||
if (!isLt) {
|
||
modal.msgError(`上传图片大小不能超过 ${props.fileSize} MB!`);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
return true;
|
||
};
|
||
|
||
const validateVideoFile = (file: File) => {
|
||
const allowedTypes = ['video/mp4', 'video/webm', 'video/ogg'];
|
||
if (!allowedTypes.includes(file.type)) {
|
||
modal.msgError('视频格式错误, 请上传 mp4/webm/ogg 格式!');
|
||
return false;
|
||
}
|
||
|
||
if (props.videoSize) {
|
||
const isLt = file.size / 1024 / 1024 < props.videoSize;
|
||
if (!isLt) {
|
||
modal.msgError(`上传视频大小不能超过 ${props.videoSize} MB!`);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
return true;
|
||
};
|
||
|
||
/* ==================== wangeditor 菜单配置 ==================== */
|
||
|
||
function checkImageQuotaBeforeUpload(): boolean {
|
||
if (!editorRef.value) return false;
|
||
const html = editorRef.value.getHtml();
|
||
const {imgNum} = measureHtml(html);
|
||
if (imgNum >= props.maxImageCount) {
|
||
modal.msgError(`图片数量不能超过 ${props.maxImageCount} 张,请先删除已插入的图片`);
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
const getUploadImageMenuConfig = () => {
|
||
if (props.type === 'base64') {
|
||
return {
|
||
allowedFileTypes: ['image/jpeg', 'image/jpg', 'image/png', 'image/svg+xml'],
|
||
customUpload(file: File, insertFn: (url: string, alt?: string, href?: string) => void) {
|
||
if (!validateImageFile(file)) return;
|
||
if (!checkImageQuotaBeforeUpload()) return;
|
||
|
||
modal.loading('正在上传图片,请稍候...');
|
||
const reader = new FileReader();
|
||
|
||
reader.onload = () => {
|
||
insertFn(reader.result as string, file.name);
|
||
modal.closeLoading();
|
||
};
|
||
|
||
reader.onerror = () => {
|
||
modal.msgError('图片插入失败');
|
||
modal.closeLoading();
|
||
};
|
||
|
||
reader.readAsDataURL(file);
|
||
}
|
||
};
|
||
}
|
||
|
||
return {
|
||
allowedFileTypes: ['image/jpeg', 'image/jpg', 'image/png', 'image/svg+xml'],
|
||
async customUpload(file: File, insertFn: (url: string, alt?: string, href?: string) => void) {
|
||
if (!validateImageFile(file)) return;
|
||
if (!checkImageQuotaBeforeUpload()) return;
|
||
|
||
modal.loading('正在上传图片,请稍候...');
|
||
try {
|
||
const result = await uploadToOss(file);
|
||
insertFn(result.url, file.name);
|
||
} catch {
|
||
modal.msgError('图片上传失败');
|
||
} finally {
|
||
modal.closeLoading();
|
||
}
|
||
}
|
||
};
|
||
};
|
||
|
||
const getUploadVideoMenuConfig = () => ({
|
||
allowedFileTypes: ['video/mp4', 'video/webm', 'video/ogg'],
|
||
async customUpload(file: File, insertFn: (url: string, poster?: string) => void) {
|
||
if (!validateVideoFile(file)) return;
|
||
|
||
modal.loading('正在上传视频,请稍候...');
|
||
try {
|
||
const result = await uploadToOss(file);
|
||
insertFn(result.url);
|
||
} catch {
|
||
modal.msgError('视频上传失败');
|
||
} finally {
|
||
modal.closeLoading();
|
||
}
|
||
}
|
||
});
|
||
|
||
const editorConfig = computed<Partial<IEditorConfig>>(() => ({
|
||
placeholder: props.simpleToolbar ? '请输入标准回复话术...' : '请输入内容',
|
||
autoFocus: false,
|
||
MENU_CONF: {
|
||
uploadImage: getUploadImageMenuConfig() as any,
|
||
uploadVideo: getUploadVideoMenuConfig() as any
|
||
},
|
||
customMenu: [
|
||
{
|
||
key: 'numberedList',
|
||
title: '有序步骤'
|
||
}
|
||
]
|
||
}));
|
||
|
||
/* ==================== 事件处理 ==================== */
|
||
|
||
function updateCounts(html: string) {
|
||
const {textLen, imgNum, linkNum} = measureHtml(html);
|
||
textCount.value = textLen;
|
||
imageCount.value = imgNum;
|
||
linkCount.value = linkNum;
|
||
emit('countChange', {textLength: textLen, imageCount: imgNum, linkCount: linkNum, htmlLength: html.length});
|
||
}
|
||
|
||
const handleChange = () => {
|
||
if (!editorRef.value) return;
|
||
const html = editorRef.value.getHtml();
|
||
console.log(html)
|
||
const {textLen, imgNum, linkNum} = measureHtml(html);
|
||
updateCounts(html);
|
||
|
||
const textOver = textLen > props.maxTextLength;
|
||
const imgOver = imgNum > props.maxImageCount;
|
||
const linkOver = linkNum > props.maxLinkCount;
|
||
|
||
if (textOver || imgOver || linkOver) {
|
||
const msgs: string[] = [];
|
||
if (textOver) msgs.push(`纯文本超过 ${props.maxTextLength} 字`);
|
||
if (imgOver) msgs.push(`图片超过 ${props.maxImageCount} 张`);
|
||
if (linkOver) msgs.push(`链接超过 ${props.maxLinkCount} 条`);
|
||
modal.msgError(msgs.join(';') + ',已自动恢复');
|
||
editorRef.value.setHtml(lastValidHtml.value);
|
||
updateCounts(lastValidHtml.value);
|
||
return;
|
||
}
|
||
|
||
lastValidHtml.value = html;
|
||
};
|
||
|
||
const syncReadOnly = () => {
|
||
const editor = editorRef.value;
|
||
if (!editor) return;
|
||
|
||
if (props.readOnly) {
|
||
editor.disable();
|
||
} else {
|
||
editor.enable();
|
||
}
|
||
};
|
||
|
||
const handleCreated = (editor: IDomEditor) => {
|
||
editorRef.value = editor;
|
||
syncReadOnly();
|
||
const html = editor.getHtml();
|
||
updateCounts(html);
|
||
lastValidHtml.value = html;
|
||
};
|
||
|
||
/* ==================== 双向数据绑定(直接透传HTML) ==================== */
|
||
|
||
watch(
|
||
() => props.modelValue,
|
||
value => {
|
||
if (value !== content.value) {
|
||
content.value = value || '';
|
||
}
|
||
},
|
||
{immediate: true}
|
||
);
|
||
|
||
watch(content, value => {
|
||
emit('update:modelValue', value);
|
||
});
|
||
|
||
watch(
|
||
() => props.readOnly,
|
||
() => {
|
||
syncReadOnly();
|
||
}
|
||
);
|
||
|
||
onBeforeUnmount(() => {
|
||
editorRef.value?.destroy();
|
||
});
|
||
</script>
|
||
|
||
<style scoped>
|
||
.editor-shell {
|
||
border: 1px solid var(--el-border-color);
|
||
border-radius: var(--el-border-radius-base);
|
||
overflow: hidden;
|
||
background: var(--el-bg-color);
|
||
}
|
||
|
||
.editor-toolbar {
|
||
border-bottom: 1px solid var(--el-border-color);
|
||
}
|
||
|
||
.editor-body {
|
||
display: flex;
|
||
flex-direction: column;
|
||
}
|
||
|
||
.editor-content {
|
||
height: 100%;
|
||
}
|
||
|
||
.editor-shell :deep(.w-e-toolbar) {
|
||
border: 0 !important;
|
||
background-color: transparent;
|
||
}
|
||
|
||
.editor-shell :deep(.w-e-text-container) {
|
||
border: 0 !important;
|
||
background-color: transparent;
|
||
}
|
||
|
||
.editor-shell :deep(.w-e-text-container [data-slate-editor]) {
|
||
min-height: inherit;
|
||
}
|
||
|
||
.editor-footer {
|
||
display: flex;
|
||
flex-direction: column;
|
||
}
|
||
|
||
.editor-tip {
|
||
padding: 12px 16px;
|
||
font-size: 13px;
|
||
color: #666;
|
||
border-top: 1px solid var(--el-border-color);
|
||
}
|
||
|
||
.demo-box {
|
||
background: #f5f7fa;
|
||
padding: 8px 12px;
|
||
margin: 6px 0;
|
||
border-radius: 4px;
|
||
}
|
||
|
||
.counter-bar {
|
||
display: flex;
|
||
justify-content: flex-end;
|
||
align-items: center;
|
||
gap: 8px;
|
||
padding: 6px 12px;
|
||
font-size: 12px;
|
||
color: #999;
|
||
border-top: 1px solid var(--el-border-color);
|
||
background: #fafafa;
|
||
}
|
||
|
||
.counter-bar .warn {
|
||
color: #e6a23c;
|
||
}
|
||
|
||
.counter-bar .danger {
|
||
color: #f56c6c;
|
||
}
|
||
|
||
.counter-bar .divider {
|
||
color: #dcdfe6;
|
||
}
|
||
</style>
|