Appearance
右键菜单 ContextMenu
createContextMenuPlugin 创建右键菜单插件:监听编辑器的 contextmenu 事件,阻止浏览器默认菜单,以鼠标坐标为锚点定位(复用 PopoverView 的 floating-ui 定位与显隐能力,placement 默认 bottom-start)。点击编辑器任意位置、Escape 键即关闭。
@qingpai/vue 提供 BaseContextMenu 与 ContextMenu 组件封装,见 组件 · ContextMenu。
用法
ts
import { createContextMenuPlugin } from '@qingpai/core'
const plugin = createContextMenuPlugin({
editor,
element: menuElement,
shouldShow: ({ node }) => node?.type.name === 'questionStem',
onNodeChange: ({ node, nodePos, pos }) => {
// 右键命中节点变化,供菜单项使用
},
})配置
ContextMenuPluginProps:
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
pluginKey | PluginKey | string | 'contextMenu' | 插件 key |
editor | Editor | — | 编辑器实例(必传) |
element | HTMLElement | — | 菜单 DOM 元素(必传) |
shouldShow | (props: ContextMenuShouldShowProps) => boolean | 恒显示 | 判断右键目标是否展示菜单 |
onNodeChange | (info: ContextMenuNodeChangeInfo) => void | — | 右键展示菜单时回调,携带命中的节点信息 |
appendTo | PopoverPluginProps['appendTo'] | 编辑器父元素 | 菜单挂载目标 |
options | PopoverPluginProps['options'] | {} | 定位选项,默认 placement: 'bottom-start' |
ts
interface ContextMenuShouldShowProps {
editor: Editor
element: HTMLElement
view: EditorView
state: EditorState
/** 右键命中的节点(右键在空白处时为 undefined) */
node?: PMNode
/** 右键命中节点的位置 */
nodePos?: number
/** 右键位置的文档坐标(供在命中处执行插入等命令) */
pos?: number
}
interface ContextMenuNodeChangeInfo {
node?: PMNode
nodePos?: number
/** 右键位置的文档坐标(供在命中处执行插入等命令) */
pos?: number
}导出的常量
| 名称 | 说明 |
|---|---|
CONTEXT_MENU_PLUGIN_KEY | 默认插件 key('contextMenu') |
导出的值与类型
createContextMenuPlugin(options: ContextMenuPluginProps):创建插件(复用PopoverView定位与显隐,差异仅在触发源)
ts
interface ContextMenuShouldShowProps {
editor: Editor
element: HTMLElement
view: EditorView
state: EditorState
/** 右键命中的节点(右键在空白处时为 undefined) */
node?: PMNode
/** 右键命中节点的位置 */
nodePos?: number
/** 右键位置的文档坐标(供在命中处执行插入等命令) */
pos?: number
}
interface ContextMenuNodeChangeInfo {
node?: PMNode
nodePos?: number
/** 右键位置的文档坐标(供在命中处执行插入等命令) */
pos?: number
}
interface ContextMenuPluginProps {
pluginKey?: PluginKey | string
editor: Editor
element: HTMLElement
/** 判断右键目标是否展示菜单(默认恒显示) */
shouldShow?: (props: ContextMenuShouldShowProps) => boolean
/** 右键展示菜单时回调(携带命中的节点信息,供菜单项使用) */
onNodeChange?: (info: ContextMenuNodeChangeInfo) => void
appendTo?: PopoverPluginProps['appendTo']
options?: PopoverPluginProps['options']
}选区保留
右键(button === 2)落在当前选区内时会阻止浏览器默认行为,避免先折叠选区——保证「选中内容 → 右键 → 菜单命令操作选区」的交互在各浏览器一致。
Source code
packages/core/src/extensions/context-menu/