context-menu.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. class ContextMenu {
  2. static Type = {
  3. PropertyItem: 'property-item',
  4. ClassListItem: 'class-list-item'
  5. };
  6. static init() {
  7. if(!DOM.get('.context-menu'))
  8. return null;
  9. if(this.instance)
  10. return this.instance;
  11. return this.instance = new ContextMenu();
  12. }
  13. constructor() {
  14. this.dom = DOM.get('.context-menu');
  15. this.items = {};
  16. }
  17. show(pos) {
  18. this.dom.style('left', `${pos.x}px`).style('top', `${pos.y}px`);
  19. this.dom.removeClass('hidden');
  20. }
  21. addDelimiter() {
  22. DOM.create({ tag: DOM.Tags.Div, cls: 'context-menu-delimiter' }, this.dom);
  23. return this;
  24. }
  25. addItem(name, text, action) {
  26. const itemAction = (e) => {
  27. action(e);
  28. this.hide();
  29. };
  30. this.items[name] = new ContextMenuItem(name, text, itemAction, this.dom).render();
  31. return this;
  32. }
  33. clear() {
  34. for(const child of this.dom.getChildren()) {
  35. const name = child.getAttribute('data-context-menu-item-name');
  36. if(name) {
  37. this.items[name].dispose();
  38. this.items[name] = null;
  39. delete this.items[name];
  40. }
  41. child.remove();
  42. }
  43. return this;
  44. }
  45. hide() {
  46. if(this.dom.hasClass('hidden'))
  47. return this;
  48. this.dom.addClass('hidden');
  49. this.clear();
  50. return this;
  51. }
  52. }
  53. window_.on(DOM.Events.MouseDown, (e) => {
  54. const contextMenu = ContextMenu.init();
  55. if(!contextMenu)
  56. return;
  57. let target = CDElement.get(e.target);
  58. while(target != null && !target.hasClass('context-menu')) {
  59. target = target.getParent();
  60. }
  61. if(target != null && target.hasClass('context-menu'))
  62. return;
  63. contextMenu.hide();
  64. });