index.tsx
3.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import {
defineComponent,
nextTick,
onMounted,
reactive,
computed,
ref,
unref,
onUnmounted,
} from 'vue';
import { props } from './props';
import Icon from '/@/components/Icon';
import { Menu, Divider } from 'ant-design-vue';
import type { ContextMenuItem } from './types';
import './index.less';
const prefixCls = 'context-menu';
export default defineComponent({
name: 'ContextMenu',
props,
setup(props) {
const wrapRef = ref<Nullable<HTMLDivElement>>(null);
const state = reactive({
show: false,
});
onMounted(() => {
nextTick(() => {
state.show = true;
});
});
onUnmounted(() => {
const el = unref(wrapRef);
el && document.body.removeChild(el);
});
const getStyle = computed(() => {
const { axis, items, styles, width } = props;
const { x, y } = axis || { x: 0, y: 0 };
const menuHeight = (items || []).length * 40;
const menuWidth = width;
const body = document.body;
return {
...(styles as any),
width: `${width}px`,
left: (body.clientWidth < x + menuWidth ? x - menuWidth : x) + 'px',
top: (body.clientHeight < y + menuHeight ? y - menuHeight : y) + 'px',
};
});
function handleAction(item: ContextMenuItem, e: MouseEvent) {
state.show = false;
const { handler, disabled } = item;
if (disabled) {
return;
}
if (e) {
e.stopPropagation();
e.preventDefault();
}
handler && handler();
}
function renderContent(item: ContextMenuItem) {
const { icon, label } = item;
const { showIcon } = props;
return (
<span style="display: inline-block; width: 100%;" onClick={handleAction.bind(null, item)}>
{showIcon && icon && <Icon class="mr-2" icon={icon} />}
<span>{label}</span>
</span>
);
}
function renderMenuItem(items: ContextMenuItem[]) {
return items.map((item, index) => {
const { disabled, label, children, divider = false } = item;
const DividerComp = divider ? <Divider key={`d-${index}`} /> : null;
if (!children || children.length === 0) {
return [
<Menu.Item disabled={disabled} class={`${prefixCls}__item`} key={label}>
{() => [renderContent(item)]}
</Menu.Item>,
DividerComp,
];
}
return !state.show ? null : (
<Menu.SubMenu key={label} disabled={disabled} popupClassName={`${prefixCls}__popup `}>
{{
title: () => renderContent(item),
default: () => [renderMenuItem(children)],
}}
</Menu.SubMenu>
);
});
}
return () => {
const { items } = props;
return !state.show ? null : (
<Menu
inlineIndent={12}
mode="vertical"
class={[prefixCls]}
ref={wrapRef}
style={unref(getStyle)}
>
{() => renderMenuItem(items)}
</Menu>
);
};
},
});