Blame view

src/components/ContextMenu/index.ts 1.78 KB
陈文彬 authored
1
2
3
import contextMenuVue from './src/index';
import { isClient } from '/@/utils/is';
import { Options, Props } from './src/types';
4
import { createVNode, render } from 'vue';
陈文彬 authored
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const menuManager: {
  doms: Element[];
  resolve: Fn;
} = {
  doms: [],
  resolve: () => {},
};
export const createContextMenu = function (options: Options) {
  const { event } = options || {};
  try {
    event.preventDefault();
  } catch (e) {
    console.log(e);
  }

  if (!isClient) return;
  return new Promise((resolve) => {
22
    const container = document.createElement('div');
陈文彬 authored
23
24
25
26
27
28
29
    const propsData: Partial<Props> = {};
    if (options.styles !== undefined) propsData.styles = options.styles;
    if (options.items !== undefined) propsData.items = options.items;
    if (options.event !== undefined) {
      propsData.customEvent = event;
      propsData.axis = { x: event.clientX, y: event.clientY };
    }
30
31
    const vm = createVNode(contextMenuVue, propsData);
    render(vm, container);
陈文彬 authored
32
33
34
    const bodyClick = function () {
      menuManager.resolve('');
    };
35
    menuManager.doms.push(container);
陈文彬 authored
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    const remove = function () {
      menuManager.doms.forEach((dom: Element) => {
        try {
          document.body.removeChild(dom);
        } catch (error) {}
      });
      document.body.removeEventListener('click', bodyClick);
      document.body.removeEventListener('scroll', bodyClick);
    };
    menuManager.resolve = function (...arg: any) {
      resolve(arg[0]);
      remove();
    };
    remove();
50
    document.body.appendChild(container);
陈文彬 authored
51
52
53
54
55
56
57
58
59
60
61
62
    document.body.addEventListener('click', bodyClick);
    document.body.addEventListener('scroll', bodyClick);
  });
};
export const unMountedContextMenu = function () {
  if (menuManager) {
    menuManager.resolve('');
    menuManager.doms = [];
  }
};

export * from './src/types';