Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add plugin contextmenu #5577

Merged
merged 9 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/g6/__tests__/demo/case/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export * from './layout-radial-configuration-translate';
export * from './layout-radial-prevent-overlap';
export * from './layout-radial-prevent-overlap-unstrict';
export * from './layout-radial-sort';
export * from './plugin-contextmenu';
export * from './plugin-grid-line';
export * from './plugin-tooltip';
export * from './plugin-watermark';
Expand Down
59 changes: 59 additions & 0 deletions packages/g6/__tests__/demo/case/plugin-contextmenu.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Graph } from '@/src';
import data from '@@/dataset/cluster.json';
import type { STDTestCase } from '../types';

export const pluginContextmenu: STDTestCase = async (context) => {
const graph = new Graph({
...context,
autoResize: true,
data,
layout: { type: 'd3force' },
plugins: [
{
type: 'contextmenu',
trigger: 'contextmenu',
getItems: () => {
return [
{ name: '展开一度关系', value: 'spread' },
{ name: '查看详情', value: 'detail' },
];
},
enable: (e: any) => e.targetType === 'node',
},
],
});

await graph.render();

pluginContextmenu.form = (panel) => {
const config = {
trigger: 'contextmenu',
};
return [
panel
.add(config, 'trigger', {
Click: 'click',
Contextmenu: 'contextmenu',
})
.name('Trigger')
.onChange((trigger: string) => {
graph.setPlugins([
{
type: 'contextmenu',
trigger,
getContextmenuItems: () => {
return [
{ name: '展开一度关系', value: 'spread' },
{ name: '查看详情', value: 'detail' },
];
},
enable: (e: any) => e.targetType === 'node',
},
]);
graph.render();
}),
];
};

return graph;
};
20 changes: 20 additions & 0 deletions packages/g6/__tests__/unit/plugins/plugin-contextmenu.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { pluginContextmenu } from '@@/demo/case';
import { createDemoGraph } from '@@/utils';

describe('plugin contextmenu', () => {
it('contextmenu', async () => {
const graph = await createDemoGraph(pluginContextmenu);
const container = graph.getCanvas().getContainer()!;

const el = container.querySelector('.g6-contextmenu') as HTMLDivElement;

expect(graph.getPlugins().length).toBe(1);
// @ts-expect-error ignore
expect(graph.getPlugins()[0].trigger).toBe('contextmenu');

expect(el.querySelector('.g6-contextmenu-li')).toBeFalsy();

await graph.destroy();
expect(container.querySelector('.g6-contextmenu')).toBeFalsy();
});
});
11 changes: 11 additions & 0 deletions packages/g6/__tests__/unit/utils/dom.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ describe('sizeOf', () => {

it('createPluginContainer', () => {
const el = createPluginContainer('test');
expect(el.getAttribute('class')).toBe('g6-test');
expect(el.style.position).toBe('absolute');
expect(el.style.display).toBe('block');
expect(el.style.top).toBe('0px');
Expand All @@ -24,6 +25,16 @@ describe('sizeOf', () => {
expect(el.style.width).toBe('100%');
expect(el.style.overflow).toBe('hidden');
expect(el.style.pointerEvents).toBe('none');
});

it('createPluginContainer cover=false', () => {
const el = createPluginContainer('test', false);
expect(el.getAttribute('class')).toBe('g6-test');
expect(el.style.position).toBe('absolute');
expect(el.style.display).toBe('block');
expect(el.style.height).not.toBe('100%');
expect(el.style.width).not.toBe('100%');
expect(el.style.overflow).not.toBe('hidden');
expect(el.style.pointerEvents).not.toBe('none');
});
});
8 changes: 4 additions & 4 deletions packages/g6/__tests__/unit/utils/extension.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ describe('extension', () => {
{ key: 'my-tooltip', type: 'tooltip' },
{ type: 'tooltip' },
{
type: 'menu',
key: 'my-context-menu',
type: 'contextmenu',
key: 'my-contextmenu',
trigger: 'contextmenu',
},
'minimap',
Expand All @@ -44,8 +44,8 @@ describe('extension', () => {
{ type: 'tooltip', key: 'my-tooltip' },
{ type: 'tooltip', key: 'plugin-tooltip-0' },
{
type: 'menu',
key: 'my-context-menu',
type: 'contextmenu',
key: 'my-contextmenu',
trigger: 'contextmenu',
},
{ type: 'minimap', key: 'plugin-minimap-1' },
Expand Down
4 changes: 3 additions & 1 deletion packages/g6/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@
"@antv/graphlib": "^2.0.2",
"@antv/hierarchy": "latest",
"@antv/layout": "^1.2.14-beta.1",
"@antv/util": "^3.3.7"
"@antv/util": "^3.3.7",
"insert-css": "^2.0.0"
},
"devDependencies": {
"@antv/g-plugin-3d": "^1.9.34",
Expand All @@ -67,6 +68,7 @@
"@antv/g-webgl": "^1.9.37",
"@antv/layout-gpu": "^1.1.5",
"@antv/layout-wasm": "^1.4.0",
"@types/insert-css": "^2.0.1",
"@types/xmlserializer": "^0.6.6",
"jest-canvas-mock": "^2.5.1",
"jest-random-mock": "^1.0.0",
Expand Down
199 changes: 199 additions & 0 deletions packages/g6/src/plugins/contextmenu.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import { insertCss } from 'insert-css';
import type { RuntimeContext } from '../runtime/types';
import type { ElementEvent } from '../types/event';
import type { Item } from '../utils/contextmenu';
import { CONTEXTMENU_CSS, getContentFromItems } from '../utils/contextmenu';
import { createPluginContainer } from '../utils/dom';
import type { BasePluginOptions } from './base-plugin';
import { BasePlugin } from './base-plugin';

/**
* <zh/> 右键菜单插件的配置项。
* <en/> The configuration item of the right-click menu plugin.
*/
export type ContextmenuOptions = BasePluginOptions & {
/**
* <zh/> 给菜单的 DOM 追加的 classname,便于自定义样式。默认是包含 `g6-contextmenu`。
* <en/> The classname appended to the menu DOM for custom styles. The default is `g6-contextmenu`.
*/
className?: string;
/**
* <zh/> 如何触发右键菜单,可以是 'click' 或者 'contextmenu',默认是 'contextmenu'。
* <en/> How to trigger the context menu, default is 'contextmenu'.
*/
trigger?: 'click' | 'contextmenu';
/**
* <zh/> 菜单显式 X、Y 方向的偏移量,默认是 [4, 4]。
* <en/> The offset X, y direction of the menu, default is [4, 4].
*/
offset?: [number, number];
/**
* <zh/> 当菜单被点击后,出发的回调方法。
* <en/> The callback method triggered when the menu is clicked.
*/
onClick?: (v: string, target: HTMLElement) => void;
/**
* <zh/> 返回菜单的项目列表,支持 `Promise` 类型的返回值。是 `getContent` 的快捷配置。
* <en/> Return the list of menu items, support the `Promise` type return value. It is a shortcut configuration of `getContent`.
*/
getItems?: (event: ElementEvent) => Item[] | Promise<Item[]>;
/**
* <zh/> 返回菜单的内容,支持 `Promise` 类型的返回值,也可以使用 `getItems` 来快捷配置。
* <en/> Return the content of menu, support the `Promise` type return value, you can also use `getItems` for shortcut configuration.
*/
getContent?: (event: ElementEvent) => HTMLElement | string | Promise<HTMLElement | string>;
/**
* <zh/> Loading 时候的菜单内容,用于 getContent 返回 Promise 的时候。
* <en/> The menu content when loading is used when getContent returns a Promise.
*/
loadingContent: HTMLElement | string;
/**
* <zh/> 插件是否可用,通过参数来判断是否支持右键菜单,默认全部可用。
* <en/> Whether the plugin is available, determine whether the right-click menu is supported through parameters, The default is all available.
*/
enable?: boolean | ((event: ElementEvent) => boolean);
};

/**
* <zh/> 支持处理事件,并显示右键菜单,在菜单点击之后,可以触发相应的事件。
* <en/> Support processing events and displaying right-click menus.
* After clicking the menu, you can trigger the corresponding event.
*/
export class Contextmenu extends BasePlugin<ContextmenuOptions> {
static defaultOptions: Partial<ContextmenuOptions> = {
trigger: 'contextmenu',
offset: [4, 4],
loadingContent: '<div class="g6-contextmenu-loading">Loading...</div>',
getContent: () => 'It is a empty context menu.',
enable: () => true,
};

private $element: HTMLElement = createPluginContainer('contextmenu', false);

constructor(context: RuntimeContext, options: ContextmenuOptions) {
super(context, Object.assign({}, Contextmenu.defaultOptions, options));

const $container = this.context.canvas.getContainer();
$container!.appendChild(this.$element);

// 设置样式
insertCss(CONTEXTMENU_CSS);

this.update(options);
}

/**
* <zh/> 根据传入的元素,显示右键菜单。
* <en/> Display the right-click menu based on the incoming element.
* @param e - 事件
*/
public async showContextmenu(e: ElementEvent) {
const { enable, offset } = this.options;

if ((typeof enable === 'function' && !enable(e)) || !enable) {
this.hideContextmenu();
return;
}

const content = await this.getDOMContent(e);

if (content instanceof HTMLElement) {
this.$element.appendChild(content);
} else {
this.$element.innerHTML = content;
}

// NOTICE: 为什么事件中的 client 是相对浏览器,而不是画布容器?
const clientRect = this.context.graph.getCanvas().getContainer()!.getBoundingClientRect();

this.$element.style.left = `${e.client.x - clientRect.left + offset[0]}px`;
this.$element.style.top = `${e.client.y - clientRect.top + offset[1]}px`;
this.$element.style.display = 'block';
}

/**
* <zh/> 隐藏右键菜单。
* <en/> Hide the right-click menu.
*/
public hideContextmenu() {
this.$element.style.display = 'none';
}

/**
* <zh/> 更新右键菜单的配置项。
* <en/> Update the configuration of the right-click menu.
* @param options - 配置项
*/
public update(options: Partial<ContextmenuOptions>) {
this.unbindEvents();
super.update(options);
this.bindEvents();
}

/**
* <zh/> 销毁右键菜单。
* <en/> Destroy the right-click menu.
*/
public destroy(): void {
this.unbindEvents();
super.destroy();
this.$element.remove();
}

private async getDOMContent(e: ElementEvent) {
const { getContent, getItems } = this.options;

if (getItems) {
return getContentFromItems(await getItems(e));
}
return await getContent(e);
}

private bindEvents() {
const { graph } = this.context;
const { trigger } = this.options;

graph.on(`canvas:${trigger}`, this.onTriggerEvent);
graph.on(`node:${trigger}`, this.onTriggerEvent);
graph.on(`edge:${trigger}`, this.onTriggerEvent);
graph.on(`combo:${trigger}`, this.onTriggerEvent);

document.addEventListener('click', this.onMenuItemClick);
}

private unbindEvents() {
const { graph } = this.context;
const { trigger } = this.options;

graph.off(`canvas:${trigger}`, this.onTriggerEvent);
graph.off(`node:${trigger}`, this.onTriggerEvent);
graph.off(`edge:${trigger}`, this.onTriggerEvent);
graph.off(`combo:${trigger}`, this.onTriggerEvent);

document.removeEventListener('click', this.onMenuItemClick);
}

private onTriggerEvent = (e: ElementEvent) => {
// `contextmenu` 事件默认会触发浏览器的右键菜单,需要阻止默认事件
// `click` 事件不需要阻止默认事件
e.preventDefault?.();
this.showContextmenu(e);
};

private onMenuItemClick = (e: MouseEvent) => {
const { onClick } = this.options;
if (e.target instanceof HTMLElement) {
if (e.target.className.includes('g6-contextmenu-li')) {
const v = e.target.getAttribute('value') as string;
onClick && onClick(v, e.target);

this.hideContextmenu();
}

// 点击其他地方,隐藏菜单
if (!this.context.graph.getCanvas().getContainer()!.contains(e.target)) {
this.hideContextmenu();
}
}
};
}
2 changes: 2 additions & 0 deletions packages/g6/src/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
export { BasePlugin } from './base-plugin';
export { Contextmenu } from './contextmenu';
export { GridLine } from './grid-line';
export { Tooltip } from './tooltip';
export { Watermark } from './watermark';

export type { BasePluginOptions } from './base-plugin';
export type { ContextmenuOptions } from './contextmenu';
export type { GridLineOptions } from './grid-line';
export type { TooltipOptions } from './tooltip';
export type { WatermarkOptions } from './watermark';