feat: 🚀 tabs

This commit is contained in:
2025-07-29 11:41:09 +08:00
parent 1a97f75546
commit 41da6b1914
10 changed files with 451 additions and 153 deletions

View File

@@ -29,8 +29,8 @@
<QuillEditor
id="mainEditor"
ref="myQuillEditor"
v-model:content="editorContent"
contentType="html"
v-model:content="editorContent"
@update:content="onContentChange"
:options="options"
/>
@@ -53,6 +53,7 @@
editable
@edit="handleTabsEdit"
@tab-change="handleTabChange"
v-if="tabsData.length"
>
<!-- 标签页标题支持编辑 -->
<el-tab-pane
@@ -112,7 +113,8 @@
<script setup name="Editor">
import { QuillEditor, Quill } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { getCurrentInstance, reactive, ref, toRaw, computed, onMounted, nextTick } from "vue";
// /computed
import { getCurrentInstance, reactive, ref, toRaw, onMounted, nextTick } from "vue";
import { generateUUID } from "@/utils";
// import { h } from "@/utils/url";
import { routerObj } from "./utils.js";
@@ -126,7 +128,7 @@ let fontSizeStyle = Quill.import("attributors/style/size");
fontSizeStyle.whitelist = ["12px", "14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px", "32px"];
Quill.register(fontSizeStyle, true);
// 自定义Blot
// 自定义Blot;
import ImageBlot from "./quill-image";
import Video from "./quill-video";
import TabsBlot from "./quill-tabs";
@@ -151,7 +153,7 @@ const activeEditor = ref("main"); // 跟踪当前活跃编辑器main/tab-索
// 标签页数据新增key作为唯一标识isEditing控制编辑状态
const tabsData = ref([]);
// 标签页编辑器ref数组
const tabEditors = ref([]);
const tabEditors = reactive([]);
// 标题编辑输入框的ref
const editInputRefs = ref([]);
const currentEditingTabsRef = ref(null);
@@ -164,7 +166,9 @@ const props = defineProps({
// 主编辑器内容双向绑定
const editorContent = computed({
get: () => props.content,
get: () => {
return props.content;
},
set: val => {
emit("update:content", val);
}
@@ -175,6 +179,7 @@ const myQuillEditor = ref(null); // 主编辑器ref
const options = reactive({
theme: "snow",
debug: "warn",
strict: false,
modules: {
toolbar: {
container: [
@@ -301,7 +306,7 @@ const handleHttpUpload = async options => {
quill = rawQuillEditor.getQuill();
} else {
const tabIndex = parseInt(activeEditor.value.split("-")[1]);
rawQuillEditor = toRaw(tabEditors.value[tabIndex]);
rawQuillEditor = toRaw(tabEditors[tabIndex]);
quill = rawQuillEditor.getQuill();
}
@@ -329,33 +334,127 @@ const handleHttpUpload = async options => {
};
// 视频上传(保持不变)
// const handleVideoUpload = async evt => {
// if (evt.target.files.length === 0) return;
// const formData = new FormData();
// formData.append("video", evt.target.files[0]);
// try {
// let rawQuillEditor = "";
// let quill = "";
// if (activeEditor.value === "main") {
// rawQuillEditor = toRaw(myQuillEditor.value);
// quill = rawQuillEditor.getQuill();
// } else {
// const tabIndex = parseInt(activeEditor.value.split("-")[1]);
// rawQuillEditor = toRaw(tabEditors.value[tabIndex]);
// quill = rawQuillEditor.getQuill();
// }
// let length = quill.selection.savedRange.index;
// const { data } = await uploadVideo(formData);
// quill.insertEmbed(length, "customVideo", {
// url: data.path,
// id: generateUUID()
// });
// uploadFileVideo.value.value = "";
// } catch (error) {
// console.log(error);
// }
// };
// 在<script setup>中替换handleVideoUpload方法
const handleVideoUpload = async evt => {
if (evt.target.files.length === 0) return;
const formData = new FormData();
formData.append("video", evt.target.files[0]);
try {
let rawQuillEditor = "";
let quill = "";
if (activeEditor.value === "main") {
rawQuillEditor = toRaw(myQuillEditor.value);
quill = rawQuillEditor.getQuill();
} else {
const tabIndex = parseInt(activeEditor.value.split("-")[1]);
rawQuillEditor = toRaw(tabEditors.value[tabIndex]);
quill = rawQuillEditor.getQuill();
}
let length = quill.selection.savedRange.index;
const { data } = await uploadVideo(formData);
quill.insertEmbed(length, "customVideo", {
url: data.path,
id: generateUUID()
const file = evt.target.files[0];
// 1. 校验视频文件
const maxSize = props.fileSizeLimit * 1024 * 1024 * 15;
if (file.size > maxSize) {
ElNotification({
title: "文件过大",
message: `视频大小不能超过 ${props.fileSizeLimit}MB`,
type: "warning"
});
uploadFileVideo.value.value = "";
return;
}
// 2. 生成视频本地URL用于生成封面不上传
const localVideoUrl = URL.createObjectURL(file);
try {
// 4. 并行处理:上传视频 + 生成并上传封面
// 4.1 上传视频到视频服务器
const videoFormData = new FormData();
videoFormData.append("video", file);
const videoRes = await uploadVideo(videoFormData); // 视频上传接口
// 校验视频上传结果(根据你的接口返回格式调整)
if (videoRes?.code !== 0) {
throw new Error(`视频上传失败: ${videoRes?.message || "未知错误"}`);
}
const videoUrl = videoRes.data.path; // 服务器返回的视频URL
console.log(localVideoUrl, "=localVideoUrl=");
// 4.2 生成封面图并上传到图片服务器
const frameBlob = await Video.captureVideoFrame(localVideoUrl);
console.log(frameBlob, "============frameBlob===========");
let coverUrl = "";
if (!frameBlob) return;
// 复用图片上传接口(与图片上传逻辑一致)
const coverFormData = new FormData();
const coverUid = generateUUID(); // 生成唯一ID
// formData.append("image", options.file);
coverFormData.append("image", frameBlob, `cover-${coverUid}.jpg`);
console.log(coverFormData, "=coverFormData=");
// 调用图片上传接口(和普通图片上传用同一个接口)
const coverRes = await uploadImg(coverFormData, routerName.value, coverUid);
// 校验封面上传结果
if (coverRes?.data?.code === 0) {
coverUrl = coverRes.data.data.path; // 服务器返回的封面URL
} else {
console.warn("封面上传失败,使用默认封面");
}
// 5. 将带封面的视频插入编辑器
insertVideoToEditor(videoUrl, coverUrl);
// 6. 上传成功提示
// loading.close();
// ElNotification({
// title: "上传成功",
// message: "视频已添加到编辑器",
// type: "success"
// });
} catch (error) {
console.log(error);
console.log(error, "==============");
} finally {
console.log("======12323232========");
// 清理资源
URL.revokeObjectURL(localVideoUrl); // 释放本地视频URL
evt.target.value = ""; // 重置文件输入框
}
};
// 辅助方法:插入视频到编辑器
const insertVideoToEditor = (videoUrl, coverUrl) => {
// 获取当前活跃的编辑器(主编辑器或标签页编辑器)
let quill;
if (activeEditor.value === "main") {
quill = toRaw(myQuillEditor.value)?.getQuill();
} else {
const tabIndex = parseInt(activeEditor.value.split("-")[1]);
quill = toRaw(tabEditors[tabIndex])?.getQuill();
}
if (quill) {
const range = quill.getSelection() || { index: 0 };
// 插入自定义视频组件携带服务器返回的视频URL和封面URL
quill.insertEmbed(range.index, "customVideo", {
url: videoUrl,
poster: coverUrl // 这里使用图片服务器返回的封面URL
});
quill.setSelection(range.index + 1); // 移动光标到视频后
}
};
// 标签页切换事件基于key切换
const handleTabChange = key => {
const tabIndex = tabsData.value.findIndex(item => item.key === key);
@@ -390,7 +489,7 @@ const handleTabsEdit = (targetKey, action) => {
// 删除标签页
const index = tabsData.value.findIndex(item => item.key === targetKey);
tabsData.value.splice(index, 1);
tabEditors.value.splice(index, 1);
tabEditors.splice(index, 1);
editInputRefs.value.splice(index, 1);
// 调整活跃编辑器索引
@@ -438,6 +537,7 @@ const finishEditTitle = index => {
// 其他方法(保持不变)
const onContentChange = content => {
console.log(content, "=content=");
emit("handleRichTextContentChange", content);
emit("update:content", content);
};
@@ -515,26 +615,25 @@ const loadTabsDataToEditor = tabs => {
};
onMounted(() => {
initTitle();
// 监听编辑按钮点击事件
const editorEl = document.querySelector(".ql-editor");
if (editorEl) {
editorEl.addEventListener("edit-tabs", e => {
console.log(1232, "测试");
console.log(e.detail.blot, "=e.detail=");
const tabsData = TabsBlot.value(e.detail.blot.domNode);
console.log(tabsData, "=tabsData=");
if (tabsData.length > 0) {
// 保存当前编辑的标签页引用
currentEditingTabsRef.value = e.detail.blot;
console.log(currentEditingTabsRef.value, "=currentEditingTabsRef.value =");
// 加载数据到弹窗
loadTabsDataToEditor(tabsData);
// 显示弹窗
outerVisible.value = true;
}
});
}
nextTick(() => {
initTitle();
// 监听编辑按钮点击事件
const editorEl = document.querySelector(".ql-editor");
if (editorEl) {
editorEl.addEventListener("edit-tabs", e => {
console.log(e.detail.blot, "=e.detail=");
const tabsData = TabsBlot.value(e.detail.blot.domNode);
if (tabsData.length > 0) {
// 保存当前编辑的标签页引用
currentEditingTabsRef.value = e.detail.blot;
// 加载数据到弹窗
loadTabsDataToEditor(tabsData);
// 显示弹窗
outerVisible.value = true;
}
});
}
});
});
defineExpose({
@@ -575,3 +674,4 @@ defineExpose({
margin: -2px 0; /* 与标签对齐 */
}
</style>
./quill-image1111

View File

@@ -55,7 +55,14 @@
@tab-change="handleTabChange"
>
<!-- 标签页标题支持编辑 -->
<el-tab-pane :label="item.title" :name="item.key" v-for="(item, index) in tabsData" :key="item.key">
<el-tab-pane
:label="item.title"
:name="item.key"
v-for="(item, index) in tabsData"
:key="item.key"
@keydown.delete.stop
@keydown.backspace.stop
>
<template #label>
<div class="tab-title-edit">
<!-- 文字显示状态 -->
@@ -64,14 +71,16 @@
</span>
<!-- 输入框编辑状态 -->
<el-input
@click.stop
@keydown.delete.stop
@keydown.backspace.stop
v-else
v-model="item.title"
max-length=""
:ref="el => (editInputRefs[index] = el)"
size="small"
class="title-input"
@blur="finishEditTitle(index)"
@keyup.enter="finishEditTitle(index)"
@keyup.esc="cancelEditTitle(index)"
/>
</div>
</template>
@@ -105,13 +114,13 @@ import { QuillEditor, Quill } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { getCurrentInstance, reactive, ref, toRaw, computed, onMounted, nextTick } from "vue";
import { generateUUID } from "@/utils";
import { h } from "@/utils/url";
// import { h } from "@/utils/url";
import { routerObj } from "./utils.js";
import { titleConfig } from "./titleConfig.js";
import { uploadVideo, uploadImg } from "@/api/modules/upload";
import { ElNotification } from "element-plus";
import { useRouter } from "vue-router";
import { useMsg } from "@/hooks/useMsg";
// 字体配置
let fontSizeStyle = Quill.import("attributors/style/size");
fontSizeStyle.whitelist = ["12px", "14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px", "32px"];
@@ -145,7 +154,7 @@ const tabsData = ref([]);
const tabEditors = ref([]);
// 标题编辑输入框的ref
const editInputRefs = ref([]);
const currentEditingTabsRef = ref(null);
// Props
const props = defineProps({
content: { type: String, default: "" },
@@ -299,7 +308,7 @@ const handleHttpUpload = async options => {
imageListDb.value.forEach(item => {
const length = quill.getLength() - 1;
quill.insertEmbed(length, "customImage", {
url: h + item.path,
url: item.path,
id: item.serverImgId || generateUUID()
});
quill.setSelection(length + 1);
@@ -338,7 +347,7 @@ const handleVideoUpload = async evt => {
let length = quill.selection.savedRange.index;
const { data } = await uploadVideo(formData);
quill.insertEmbed(length, "customVideo", {
url: h + data.path,
url: data.path,
id: generateUUID()
});
uploadFileVideo.value.value = "";
@@ -357,6 +366,9 @@ const handleTabChange = key => {
// 标签页增删事件
const handleTabsEdit = (targetKey, action) => {
if (action === "add") {
if (tabsData.value.length > 5) {
return useMsg("error", "标签页已达上限 !");
}
// 新增标签页生成唯一key默认标题初始不处于编辑状态
const newKey = `tab_${generateUUID()}`;
const newIndex = tabsData.value.length;
@@ -440,15 +452,33 @@ const setTabsInfo = () => {
const handleBeforeClose = () => {
setTabsInfo();
};
//确认
// 确认按钮点击事件(修改后)
const handleQR = () => {
const quill = toRaw(myQuillEditor.value)?.getQuill();
if (quill) {
const range = quill.getSelection(true);
quill.insertEmbed(range.index, "tabs", tabsData.value);
quill.setSelection(range.index + 1);
setTabsInfo();
if (!quill) return;
if (!tabsData.value.length) {
return useMsg("error", "标签页内容为空 !");
}
const range = quill.getSelection(true);
// 判断是否是编辑已有标签页(通过 currentEditingTabsRef 是否有值)
if (currentEditingTabsRef.value) {
// 1. 编辑模式:更新原有标签页组件
const blot = currentEditingTabsRef.value;
// 更新 blot 的数据(触发 DOM 更新)
blot.updateContents(tabsData.value); // 需要在 TabsBlot 中添加 updateContents 方法
// 清除编辑状态标记
currentEditingTabsRef.value = null;
} else {
// 2. 新增模式:插入新的标签页组件
quill.insertEmbed(range.index, "tabs", tabsData.value);
// 关键:在标签页前方插入一个空段落(确保顶部有空间)
// quill.insertText(range.index, "\n"); // 插入换行
quill.setSelection(range.index + 1);
quill.insertText(range.index, "\n"); // 插入换行
}
// 关闭弹窗并清空临时数据
setTabsInfo();
};
//取消
const handleQX = () => {
@@ -462,9 +492,49 @@ const initTitle = () => {
if (tip) tip.setAttribute("title", item.title);
});
};
// 定义 loadTabsDataToEditor 函数
const loadTabsDataToEditor = tabs => {
// 清空现有数据
tabsData.value = [];
// 转换原始标签数据为编辑所需格式添加key和编辑状态
tabs.forEach((tab, index) => {
tabsData.value.push({
key: `tab_${generateUUID()}`, // 生成唯一key
title: tab.title || `标签${index + 1}`, // 避免空标题
content: tab.content || "", // 标签页内容
isEditing: false // 编辑状态标记
});
});
// 激活第一个标签页(如果有数据)
nextTick(() => {
if (tabsData.value.length > 0) {
activeName.value = tabsData.value[0].key;
activeEditor.value = "tab-0";
}
});
};
onMounted(() => {
initTitle();
// 监听编辑按钮点击事件
const editorEl = document.querySelector(".ql-editor");
if (editorEl) {
editorEl.addEventListener("edit-tabs", e => {
console.log(1232, "测试");
console.log(e.detail.blot, "=e.detail=");
const tabsData = TabsBlot.value(e.detail.blot.domNode);
console.log(tabsData, "=tabsData=");
if (tabsData.length > 0) {
// 保存当前编辑的标签页引用
currentEditingTabsRef.value = e.detail.blot;
console.log(currentEditingTabsRef.value, "=currentEditingTabsRef.value =");
// 加载数据到弹窗
loadTabsDataToEditor(tabsData);
// 显示弹窗
outerVisible.value = true;
}
});
}
});
defineExpose({
@@ -488,63 +558,21 @@ defineExpose({
user-select: text !important;
}
/* 标签页样式 */
// /* 标签页样式 */
.quill-tabs {
margin: 15px 0;
overflow: hidden;
border: 1px solid #dddddd;
border-radius: 4px;
}
/* 用伪元素添加图标(可替换为自己的图标) */
// /* 用伪元素添加图标(可替换为自己的图标) */
.ql-tabs::before {
font-size: 16px;
content: "T"; /* 用 emoji 或字体图标 */
}
.quill-tab-list {
display: flex;
background-color: #f8f9fa;
border-bottom: 1px solid #dddddd;
}
.quill-tab-button {
padding: 10px 15px;
font-weight: 500;
cursor: pointer;
background: transparent;
border: none;
transition: background-color 0.2s;
}
.quill-tab-button.active {
color: #007bff;
background-color: white;
border-bottom: 2px solid #007bff;
}
.quill-tab-content-list {
padding: 15px;
}
.quill-tab-content {
display: none;
}
.quill-tab-content.active {
display: block;
}
/* 标签页标题编辑样式 */
.tab-title-edit {
display: flex;
align-items: center;
.title-text {
display: inline-block;
min-width: 60px;
padding: 0 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
cursor: pointer;
}
.title-input {
width: 100px;
margin: -2px 0; /* 与标签对齐 */
}
.title-input {
width: 100px;
margin: -2px 0; /* 与标签对齐 */
}
</style>
./quill-image1111

View File

@@ -11,8 +11,6 @@ class ImageBlot extends BlockEmbed {
}
// 允许通过键盘删除
deleteAt(index, length) {
console.log(index, length, "===============>");
console.log("===========super===========");
super.deleteAt(index, length);
}
static value(node) {

View File

@@ -0,0 +1,25 @@
import { Quill } from "@vueup/vue-quill";
let BlockEmbed = Quill.import("blots/block/embed");
class ImageBlot extends BlockEmbed {
static create(value) {
let node = super.create();
node.setAttribute("src", value.url);
node.setAttribute("id", value.id);
console.log("图片信息", node);
return node;
}
// 允许通过键盘删除
deleteAt(index, length) {
super.deleteAt(index, length);
}
static value(node) {
return {
url: node.getAttribute("src"),
id: node.getAttribute("id")
};
}
}
ImageBlot.blotName = "customImage";
ImageBlot.tagName = "img";
export default ImageBlot;

View File

@@ -38,6 +38,7 @@ class TabsBlot extends BlockEmbed {
scrollbar-width: none;
-ms-overflow-style: none;
overflow-y: hidden;
overflow-x: auto;
height: auto;
`
);
@@ -50,15 +51,6 @@ class TabsBlot extends BlockEmbed {
tabScrollContainer.style.scrollbarWidth = "none";
tabScrollContainer.style.msOverflowStyle = "none";
// // 关键:隐藏滚动条但保留功能
// tabScrollContainer.innerHTML = `
// <style>
// .m-quill-tab-scroll-container::-webkit-scrollbar {
// display: none; /* Chrome, Safari 隐藏滚动条 */
// }
// </style>
// `;
// 标签栏 - 保持原有样式不变
const tabList = document.createElement("div");
tabList.className = "m-quill-tab-list";
@@ -66,7 +58,7 @@ class TabsBlot extends BlockEmbed {
"style",
`
display: flex;
border-bottom: 1px solid #dddddd;
border-bottom: 2px solid #dddddd;
min-width: max-content; /* 确保内容撑开容器 */
`
);
@@ -85,8 +77,10 @@ class TabsBlot extends BlockEmbed {
cursor: pointer;
background: transparent;
border: none;
margin-right: 5px; /* 增大间距 */
padding-bottom:14px;
margin-right:3%; /* 增大间距 */
cursor: pointer;
white-space:nowrap;
font-size:16px;
${index === 0 ? "color: #1f2635; border-bottom: 3px solid #537CD8;font-size:16px;" : ""}
`
@@ -106,7 +100,8 @@ class TabsBlot extends BlockEmbed {
margin-left: auto;
color: #606266;
cursor: pointer;
width:50px;
width:60px;
padding-left:20px;
background: transparent;
border: none;
display:block;
@@ -134,7 +129,7 @@ class TabsBlot extends BlockEmbed {
"style",
`
display: ${index === 0 ? "block" : "none"};
min-height: 50px;
min-height: 50px;
`
);
panel.contentEditable = "false";
@@ -152,13 +147,14 @@ class TabsBlot extends BlockEmbed {
(function() {
const container = document.currentScript.parentElement;
const isAdmin = window.location.pathname.includes('/admin');
const editBtn1 = container.querySelector('.m-quill-tab-edit-btn');
const editBtn1 = container.querySelector('.m-quill-tab-edit-btn');
// 仅在非管理系统(文章网站)隐藏编辑按钮,管理系统保持显示
if (!isAdmin && editBtn1) {
editBtn1.style.display = 'none'; // 文章网站隐藏按钮
} else if (isAdmin && editBtn1) {
editBtn1.style.display = 'block'; // 管理系统强制显示按钮
editBtn1.style.width='60px';
editBtn1.style.minWidth='60px';
}
// 非管理系统才执行标签切换逻辑(管理系统不执行)
@@ -174,7 +170,9 @@ class TabsBlot extends BlockEmbed {
cursor: pointer;
background: transparent;
font-size:16px;
margin-right: 5px;
white-space:nowrap;
padding-bottom:14px;
margin-right:3%;
color: #8f9099;
border: none;
\${i === index ?
@@ -186,6 +184,16 @@ class TabsBlot extends BlockEmbed {
contentPanels.forEach((panel, i) => {
panel.style.display = i === index ? 'block' : 'none';
});
// 添加滚动逻辑到自执行函数中
const scrollContainer = container.querySelector(".m-quill-tab-scroll-container");
const activeBtn = tabButtons[index];
if (scrollContainer && activeBtn) {
activeBtn.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "center"
});
}
});
});
}
@@ -280,13 +288,14 @@ class TabsBlot extends BlockEmbed {
btn.setAttribute(
"style",
`
font-weight: 900;
cursor: pointer;
background: transparent;
border: none;
font-size:16px;
margin-right: 5px;
padding-bottom:14px;
margin-right:3%;
white-space:nowrap;
color: #8f9099;
border-bottom: 3px solid transparent;
${i === index ? "color: #1f2635;border-bottom: 3px solid #537CD8;font-size:16px;" : ""}
@@ -367,7 +376,9 @@ class TabsBlot extends BlockEmbed {
cursor: pointer;
background: transparent;
border: none;
margin-right: 5px;
padding-bottom:14px;
margin-right:3%;
white-space:nowrap;
font-size:16px;
${index === 0 ? "color: #1f2635; border-bottom: 3px solid #537CD8;font-size:16px;" : ""}
`

View File

@@ -1,32 +1,99 @@
import { Quill } from "@vueup/vue-quill";
// 源码中是import直接倒入这里要用Quill.import引入
const BlockEmbed = Quill.import("blots/block/embed");
const Link = Quill.import("formats/link");
const ATTRIBUTES = ["height", "width"];
const ATTRIBUTES = ["height", "width", "poster"];
class Video extends BlockEmbed {
static create(value) {
let node = super.create();
// 添加video标签所需的属性
// 基础视频属性
node.setAttribute("controls", "controls");
node.setAttribute("playsinline", "true");
node.setAttribute("webkit-playsinline", "true");
node.setAttribute("type", "video/mp4");
// poster 属性指定视频下载时显示的图像,或者在用户点击播放按钮前显示的图像。
// console.log(value.url, "= value.poster=");
// node.setAttribute("poster", this.sanitize(value.url));
node.setAttribute("src", this.sanitize(value.url));
// 处理视频URL添加时间片段定位到0.001秒(避开黑屏)
const baseUrl = this.sanitize(value.url);
const videoUrl = baseUrl.includes("#") ? `${baseUrl}&t=0.001` : `${baseUrl}#t=0.001`;
node.setAttribute("src", videoUrl);
// 临时封面(加载中显示)
node.setAttribute(
"poster",
"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='600' height='300' viewBox='0 0 600 300'%3E%3Crect width='100%25' height='100%25' fill='%23f0f0f0'/%3E%3Ccircle cx='300' cy='150' r='40' fill='%23ccc'/%3E%3Cpolygon points='300,130 330,160 270,160' fill='white'/%3E%3C/svg%3E"
);
// 自动截取封面未提供poster时
if (!value.poster) {
this.captureFrameAsBlob(videoUrl, node);
} else {
node.setAttribute("poster", this.sanitize(value.poster));
}
// width: 600px;
// height: 300px;
// object-fit: contain;
// 视频样式
node.setAttribute(
"style",
`
width: 600px;
height: 300px;
`
);
return node;
}
/**
* 生成视频帧Blob核心方法返回Promise
* @param {string} videoUrl - 视频的本地Blob URL
* @returns {Promise<Blob|null>} - 视频帧Blob或null
*/
/**
* 将视频Blob URL转换为JPG图片Blob
* @param {string} videoBlobUrl - 本地视频Blob URLblob:xxx
* @returns {Promise<Blob|null>} - JPG格式图片Blob失败返回null
*/
static async captureVideoFrame(videoBlobUrl) {
return new Promise(resolve => {
// 1. 创建视频元素加载Blob
const video = document.createElement("video");
video.src = videoBlobUrl;
video.muted = true;
video.playsInline = true;
video.preload = "auto";
// 2. 视频可播放时开始转换
video.oncanplay = () => {
// 3. 创建Canvas绘制视频帧
const canvas = document.createElement("canvas");
canvas.width = video.videoWidth || 640; // 使用视频实际宽度
canvas.height = video.videoHeight || 360; // 使用视频实际高度
const ctx = canvas.getContext("2d");
// 绘制视频当前帧到Canvas
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
// 4. 将Canvas转换为JPG Blob
canvas.toBlob(
blob => {
console.log(blob, "================>");
video.remove(); // 清理视频元素
resolve(blob || null); // 返回JPG Blob
},
"image/jpeg", // 强制JPG格式
0.8 // 图片质量0-1
);
};
// 错误处理
video.onerror = () => {
video.remove();
resolve(null);
};
});
}
// 以下方法保持不变
static formats(domNode) {
return ATTRIBUTES.reduce((formats, attribute) => {
if (domNode.hasAttribute(attribute)) {
@@ -41,15 +108,14 @@ class Video extends BlockEmbed {
}
static value(domNode) {
// 设置自定义的属性值
return {
url: domNode.getAttribute("src")
// poster: domNode.getAttribute("src")
url: domNode.getAttribute("src").split("#")[0],
poster: domNode.getAttribute("poster") || ""
};
}
format(name, value) {
if (ATTRIBUTES.indexOf(name) > -1) {
if (ATTRIBUTES.includes(name)) {
if (value) {
this.domNode.setAttribute(name, value);
} else {
@@ -61,12 +127,13 @@ class Video extends BlockEmbed {
}
html() {
const { video } = this.value();
return `<a href="${video}">${video}</a>`;
const { url, poster } = this.value();
return `<video src="${url}" ${poster ? `poster="${poster}"` : ""} controls playsinline webkit-playsinline ></video>`;
}
}
Video.blotName = "customVideo"; // 这里不用改不用iframe直接替换掉原来如果需要也可以保留原来的这里用个新的blot
Video.className = "ql-video"; // 可添加样式,看实际使用需要
Video.tagName = "video"; // 用video标签替换iframe
//style="width:600px;height:300px;"
Video.blotName = "customVideo";
// Video.className = "ql-video";
Video.tagName = "video";
export default Video;

View File

@@ -0,0 +1,72 @@
import { Quill } from "@vueup/vue-quill";
// 源码中是import直接倒入这里要用Quill.import引入
const BlockEmbed = Quill.import("blots/block/embed");
const Link = Quill.import("formats/link");
const ATTRIBUTES = ["height", "width"];
class Video extends BlockEmbed {
static create(value) {
let node = super.create();
// 添加video标签所需的属性
node.setAttribute("controls", "controls");
node.setAttribute("playsinline", "true");
node.setAttribute("webkit-playsinline", "true");
node.setAttribute("type", "video/mp4");
// poster 属性指定视频下载时显示的图像,或者在用户点击播放按钮前显示的图像。
// console.log(value.url, "= value.poster=");
// node.setAttribute("poster", this.sanitize(value.url));
node.setAttribute("src", this.sanitize(value.url));
node.setAttribute(
"style",
`
width: 600px;
height: 300px;
`
);
return node;
}
static formats(domNode) {
return ATTRIBUTES.reduce((formats, attribute) => {
if (domNode.hasAttribute(attribute)) {
formats[attribute] = domNode.getAttribute(attribute);
}
return formats;
}, {});
}
static sanitize(url) {
return Link.sanitize(url);
}
static value(domNode) {
// 设置自定义的属性值
return {
url: domNode.getAttribute("src")
// poster: domNode.getAttribute("src")
};
}
format(name, value) {
if (ATTRIBUTES.indexOf(name) > -1) {
if (value) {
this.domNode.setAttribute(name, value);
} else {
this.domNode.removeAttribute(name);
}
} else {
super.format(name, value);
}
}
html() {
const { video } = this.value();
return `<a href="${video}">${video}</a>`;
}
}
Video.blotName = "customVideo"; // 这里不用改不用iframe直接替换掉原来如果需要也可以保留原来的这里用个新的blot
Video.className = "ql-video"; // 可添加样式,看实际使用需要
Video.tagName = "video"; // 用video标签替换iframe
export default Video;