contextmenu.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Package: svgedit.contextmenu
  3. *
  4. * Licensed under the Apache License, Version 2
  5. *
  6. * Author: Adam Bender
  7. */
  8. // Dependencies:
  9. // 1) jQuery (for dom injection of context menus)
  10. var svgedit = svgedit || {};
  11. (function() {
  12. var self = this;
  13. if (!svgedit.contextmenu) {
  14. svgedit.contextmenu = {};
  15. }
  16. self.contextMenuExtensions = {}
  17. var addContextMenuItem = function(menuItem) {
  18. // menuItem: {id, label, shortcut, action}
  19. if (!menuItemIsValid(menuItem)) {
  20. console
  21. .error("Menu items must be defined and have at least properties: id, label, action, where action must be a function");
  22. return;
  23. }
  24. if (menuItem.id in self.contextMenuExtensions) {
  25. console.error('Cannot add extension "' + menuItem.id
  26. + '", an extension by that name already exists"');
  27. return;
  28. }
  29. // Register menuItem action, see below for deferred menu dom injection
  30. console.log("Registed contextmenu item: {id:"+ menuItem.id+", label:"+menuItem.label+"}");
  31. self.contextMenuExtensions[menuItem.id] = menuItem;
  32. //TODO: Need to consider how to handle custom enable/disable behavior
  33. }
  34. var hasCustomHandler = function(handlerKey) {
  35. return self.contextMenuExtensions[handlerKey] && true;
  36. }
  37. var getCustomHandler = function(handlerKey) {
  38. return self.contextMenuExtensions[handlerKey].action;
  39. }
  40. var injectExtendedContextMenuItemIntoDom = function(menuItem) {
  41. if (Object.keys(self.contextMenuExtensions).length == 0) {
  42. // all menuItems appear at the bottom of the menu in their own container.
  43. // if this is the first extension menu we need to add the separator.
  44. $("#cmenu_canvas").append("<li class='separator'>");
  45. }
  46. var shortcut = menuItem.shortcut || "";
  47. $("#cmenu_canvas").append("<li class='disabled'><a href='#" + menuItem.id + "'>"
  48. + menuItem.label + "<span class='shortcut'>"
  49. + shortcut + "</span></a></li>");
  50. }
  51. var menuItemIsValid = function(menuItem) {
  52. return menuItem && menuItem.id && menuItem.label && menuItem.action && typeof menuItem.action == 'function';
  53. }
  54. // Defer injection to wait out initial menu processing. This probably goes away once all context
  55. // menu behavior is brought here.
  56. svgEditor.ready(function() {
  57. for (menuItem in contextMenuExtensions) {
  58. injectExtendedContextMenuItemIntoDom(contextMenuExtensions[menuItem]);
  59. }
  60. });
  61. svgedit.contextmenu.resetCustomMenus = function(){self.contextMenuExtensions = {}}
  62. svgedit.contextmenu.add = addContextMenuItem;
  63. svgedit.contextmenu.hasCustomHandler = hasCustomHandler;
  64. svgedit.contextmenu.getCustomHandler = getCustomHandler;
  65. })();