import type { IButtonMenu, IDomEditor } from '@wangeditor/editor' import { Boot } from '@wangeditor/editor' // 当前的点击处理器,始终指向最新传入的函数 let currentClickHandler: (() => void) | null = null // 是否已经注册过菜单 let hasRegistered = false class PreviewButtonMenu implements IButtonMenu { title = '预览' iconSvg = ` ` tag = 'button' getValue(): string | boolean { return '' } isActive(): boolean { return false } isDisabled(): boolean { return false } exec(editor: IDomEditor): void { if (this.isDisabled()) return currentClickHandler?.() // 始终执行最新的回调 } } // 提供注册函数,允许多次调用,但只注册一次菜单 export function registerPreviewMenu(handleClick: () => void) { currentClickHandler = handleClick if (hasRegistered) return try { Boot.registerMenu({ key: 'preview', factory: () => new PreviewButtonMenu(), }) hasRegistered = true } catch (e) { if (!/duplicate/i.test(String(e))) { console.warn('注册预览菜单失败:', e) } } } // 菜单插入配置 export const toolbarConfig = { excludeKeys: ['codeBlock', 'fullScreen', 'code'], insertKeys: { index: 32, keys: ['preview'], }, }