| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207 |
- /**
- * 富文本编辑器(@wangeditor/editor)素材库上传与「从素材库选择」公共封装。
- *
- * - buildEditorAssetMenuConf:生成 MENU_CONF.uploadImage / uploadVideo,
- * 上传端点统一指向 /api/admin/file-record/upload(fieldName=file,Bearer 认证),
- * 使编辑器内粘贴/拖拽/按钮上传自动写入 file_record(素材库)。
- * customInsert 用 resolveAssetUrl 规整 URL,修复旧代码 baseURL+url 在京东云
- * 绝对地址下产生的双前缀 bug。
- * - insertAssetIntoEditor:把素材库选中的记录插入编辑器光标处(图片/视频节点)。
- */
- import { Message } from 'element-ui'
- import { Boot } from '@wangeditor/editor'
- import { resolveAssetUrl } from './asset'
- const BASE_URL = process.env.VUE_APP_BASE_API || ''
- export function getUploadHeaders() {
- const token = localStorage.getItem('token')
- return token ? { Authorization: 'Bearer ' + token } : {}
- }
- function makeCustomInsert() {
- return function customInsert(res, insertFn) {
- if (!res) return
- if (res.code !== 200) {
- Message.error((res.message || '上传失败') + '(素材未入库)')
- return
- }
- const data = res.data
- const url = data && data.url ? data.url : data
- if (!url) return
- insertFn(resolveAssetUrl(url))
- }
- }
- /**
- * 编辑器顶层 config.customAlert 工厂。
- *
- * <p>注意:wangEditor 从编辑器顶层 config.customAlert 读取(不是 MENU_CONF.uploadImage.customAlert),
- * 因此必须挂在 editorConfig 根节点上:
- * <pre>
- * editorConfig = {
- * customAlert: getEditorCustomAlert(),
- * MENU_CONF: buildEditorAssetMenuConf({ category: 'articles' })
- * }
- * </pre>
- */
- export function getEditorCustomAlert() {
- // 注意:wangEditor 从编辑器顶层 config.customAlert 读取(不是 MENU_CONF.uploadImage.customAlert)
- return function customAlert(msg, type) {
- Message({ message: msg, type: type || 'error' })
- }
- }
- function makeOnError(label, maxSizeMB) {
- return function onError(file) {
- const name = (file && file.name) || label
- Message.error(name + ' 上传失败,' + label + '不能超过 ' + maxSizeMB + 'MB')
- }
- }
- /**
- * 生成 wangEditor MENU_CONF 的 uploadImage / uploadVideo 配置。
- *
- * @param {Object} opts
- * @param {String} opts.category 上传入库的素材分类,默认 general
- * @param {Number} opts.maxImageSize 图片上限(MB),默认 5
- * @param {Number} opts.maxVideoSize 视频上限(MB),默认 50
- * @returns {{uploadImage:Object, uploadVideo:Object}}
- */
- export function buildEditorAssetMenuConf(opts = {}) {
- const category = opts.category || 'general'
- const maxImageSize = opts.maxImageSize || 5
- const maxVideoSize = opts.maxVideoSize || 50
- return {
- uploadImage: {
- server: BASE_URL + '/api/admin/file-record/upload',
- headers: getUploadHeaders(),
- meta: { category },
- maxNumberOfFiles: 1,
- maxFileSize: maxImageSize * 1024 * 1024,
- fieldName: 'file',
- customInsert: makeCustomInsert(),
- onError: makeOnError('图片', maxImageSize)
- },
- uploadVideo: {
- server: BASE_URL + '/api/admin/file-record/upload',
- headers: getUploadHeaders(),
- meta: { category },
- maxNumberOfFiles: 1,
- maxFileSize: maxVideoSize * 1024 * 1024,
- fieldName: 'file',
- timeout: 5 * 60 * 1000,
- allowedFileTypes: ['video/*'],
- customInsert: makeCustomInsert(),
- onError: makeOnError('视频', maxVideoSize)
- }
- }
- }
- /**
- * 把素材库选中的记录插入编辑器当前光标处。
- *
- * @param {Object} editor wangEditor 实例
- * @param {Object} record 素材库记录(含 url/fileType)
- * @param {String} type image | video(不传时按 record.fileType 推断)
- */
- export function insertAssetIntoEditor(editor, record, type) {
- if (!editor || !record) return
- const url = resolveAssetUrl(record.url)
- if (!url) return
- const resolvedType = type || (record.fileType === 'video' ? 'video' : 'image')
- try {
- if (resolvedType === 'video') {
- editor.insertNode({
- type: 'video',
- src: url,
- poster: '',
- width: 'auto',
- height: 'auto',
- children: [{ text: '' }]
- })
- } else {
- editor.insertNode({
- type: 'image',
- src: url,
- alt: '',
- href: '',
- style: {},
- children: [{ text: '' }]
- })
- }
- } catch (e) {
- console.error('编辑器插入素材失败', e)
- try {
- editor.dangerouslyInsertHtml(
- resolvedType === 'video' ? '<video src="' + url + '"></video>' : '<img src="' + url + '"/>'
- )
- } catch (e2) {
- console.error('编辑器 HTML 兜底插入失败', e2)
- }
- }
- }
- // ==================== 编辑器工具栏「素材库」菜单 ====================
- export const ASSET_MENU_KEY = 'assetLibrary'
- let assetMenuHandler = null
- let assetMenuRegistered = false
- /**
- * 注册「素材库」按钮点击回调。页面在 created 时绑定,exec 时调用。
- * @param {Function} fn
- */
- export function setAssetMenuHandler(fn) {
- assetMenuHandler = typeof fn === 'function' ? fn : null
- }
- /**
- * 向 wangEditor 注册自定义「素材库」工具栏菜单(全局只注册一次)。
- * 必须在编辑器渲染前调用(页面 created 即可)。
- */
- export function registerAssetLibraryMenu() {
- if (assetMenuRegistered) return
- assetMenuRegistered = true
- Boot.registerMenu({
- key: ASSET_MENU_KEY,
- factory() {
- return {
- tag: 'button',
- title: '素材库',
- iconSvg: '<svg viewBox="0 0 1024 1024" width="16" height="16"><path fill="currentColor" d="M160 192h704a64 64 0 0 1 64 64v512a64 64 0 0 1-64 64H160a64 64 0 0 1-64-64V256a64 64 0 0 1 64-64zm0 64v512h704V256H160zm96 96h160a32 32 0 0 1 32 32v96a32 32 0 0 1-32 32H256a32 32 0 0 1-32-32v-96a32 32 0 0 1 32-32zm0 224h512v48H256v-48z"/></svg>',
- getValue() { return '' },
- isActive() { return false },
- isDisabled() { return false },
- exec() {
- if (assetMenuHandler) assetMenuHandler()
- }
- }
- }
- })
- }
- /**
- * 生成带「素材库」按钮的工具栏配置。
- * @param {Object} extra 额外 toolbarConfig 字段
- */
- export function buildAssetToolbarConfig(extra) {
- return Object.assign(
- { insertKeys: { index: 0, keys: [ASSET_MENU_KEY] } },
- extra || {}
- )
- }
- export default {
- buildEditorAssetMenuConf,
- insertAssetIntoEditor,
- getEditorCustomAlert,
- getUploadHeaders,
- registerAssetLibraryMenu,
- setAssetMenuHandler,
- buildAssetToolbarConfig,
- ASSET_MENU_KEY
- }
|